最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
你可以使用累加器,也就是减少。
['a','b','c'].reduce(function(result, item, index, array) {
result[index] = item; //a, b, c
return result;
}, {}) //watch out the empty {}, which is passed as "result"
传递一个空对象{}作为起始点;然后递增地“增大”该对象。 在迭代结束时,结果将是{"0":"a", "1": "b", "2": "c"}
如果数组是键值对对象的集合:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item) {
var key = Object.keys(item)[0]; //first property: a, b, c
result[key] = item[key];
return result;
}, {});
将产生:{a: 1, b: 2, c: 3}
为了完整起见,reduceRight允许你以相反的顺序遍历数组:
[{ a: 1},{ b: 2},{ c: 3}].reduceRight(/* same implementation as above */)
将产生:{c:3, b:2, a:1}
你的蓄能器可以为你的特定用途的任何类型。例如,为了交换数组中对象的键和值,传递[]:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
var key = Object.keys(item)[0]; //first property: a, b, c
var value = item[key];
var obj = {};
obj[value] = key;
result.push(obj);
return result;
}, []); //an empty array
将产生:[{1:"a"}, {2: "b"}, {3: "c"}]
与map不同,reduce不能用作1-1映射。您可以完全控制要包含或排除的项。因此,reduce可以实现过滤器的功能,这使得reduce非常通用:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
if(index !== 0) { //skip the first item
result.push(item);
}
return result;
}, []); //an empty array
将产生:[{2:"b"}, {3: "c"}]
警告:减少和对象。关键是ECMA第5版的一部分;你应该为不支持它们的浏览器(尤其是IE8)提供一个polyfill。
请参阅Mozilla的默认实现。
其他回答
如果你正在使用angularjs,你可以使用angular。Extend,与$的效果相同。jquery的扩展。
var newObj = {};
angular.extend(newObj, ['a','b','c']);
如果你喜欢联机程序,IE8不再是一个问题(因为它应该是)
['a','b','c'].reduce((m,e,i) => Object.assign(m, {[i]: e}), {});
继续在浏览器控制台上尝试它
它可以像这样更啰嗦:
['a','b','c'].reduce(function(memo,elm,idx) {
return Object.assign(memo, {[idx]: elm});
}, {});
但还是排除了IE8的可能性。如果必须使用IE8,那么你可以像这样使用lodash/下划线:
_.reduce(['a','b','c'], function(memo,elm,idx) {
return Object.assign(memo, {[idx]: elm});
}, {})
尝试使用反射从数组项复制到对象。
var arr =['aa:23','bb:44','cc:55']
var obj ={}
arr.forEach(e => {
var ee = e.split(':')
Reflect.set(obj,ee[0],ee[1])
});
console.log(obj) // { aa: '23', bb: '44', cc: '55' }
我的版本数组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
}
从Lodash 3.0.0开始,你可以使用_.toPlainObject
var obj = _.toPlainObject(['a', 'b', 'c']); 控制台.log(卷); <script src=“https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js”></script>