最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行
const nodes = {
node1: {
interfaces: {if1: {}, if2: {}}
},
node2: {
interfaces: {if3: {}, if4: {}}
},
node3: {
interfaces: {if5: {}, if6: {}}
},
}
解决方案是结合使用reduce和对象扩展:
const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})
其他回答
这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行
const nodes = {
node1: {
interfaces: {if1: {}, if2: {}}
},
node2: {
interfaces: {if3: {}, if4: {}}
},
node3: {
interfaces: {if5: {}, if6: {}}
},
}
解决方案是结合使用reduce和对象扩展:
const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})
我的版本数组json在JS。只需要复制/粘贴并使用它。这是不是很棒?我喜欢我在StackOverflow上发现的这类函数。
function array2json(arr) {
var parts = [];
var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
for(var key in arr) {
var value = arr[key];
if(typeof value == "object") { //Custom handling for arrays
if(is_list) parts.push(array2json(value)); /* :RECURSION: */
else parts[key] = array2json(value); /* :RECURSION: */
} else {
var str = "";
if(!is_list) str = '"' + key + '":';
//Custom handling for multiple data types
if(typeof value == "number") str += value; //Numbers
else if(value === false) str += 'false'; //The booleans
else if(value === true) str += 'true';
else str += '"' + value + '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
parts.push(str);
}
}
var json = parts.join(",");
if(is_list) return '[' + json + ']';//Return numerical JSON
return '{' + json + '}';//Return associative JSON
}
更多的浏览器支持和更灵活的方法是使用一个正常的循环,比如:
const arr = ['a', 'b', 'c'],
obj = {};
for (let i=0; i<arr.length; i++) {
obj[i] = arr[i];
}
但现代的方法也可以使用展开运算符,比如:
{...arr}
或对象赋值:
Object.assign({}, ['a', 'b', 'c']);
两者都会返回:
{0: "a", 1: "b", 2: "c"}
更面向对象的方法:
Array.prototype.toObject = function() {
var Obj={};
for(var i in this) {
if(typeof this[i] != "function") {
//Logic here
Obj[i]=this[i];
}
}
return Obj;
}
我将使用Array.of()简单地做到这一点。Array of有能力使用它的context作为构造函数。
注2:of函数是一个有意通用的工厂方法;它 不要求它的this值是数组构造函数。 因此,它可以传递给其他构造函数或由其他构造函数继承 可以使用单个数值参数调用。
因此,我们可以将array .of()绑定到一个函数,并生成类似object的数组。
虚函数(){}; var thingy = Array.of.apply(dummy,[1,2,3,4]); console.log(页面);
通过使用array .of(),甚至可以进行数组子类化。