简体   繁体   English

热门使用reduce将对象数组转换为单个对象

[英]Hot to use reduce to convert a array of objects to a single object

i'm trying to work with reduce or map, but i'm a noob some times. 我正在尝试使用reduce或map,但有时候我是一个菜鸟。

i'm trying to use this function to return a single array from the objects. 我正在尝试使用此函数从对象返回单个数组。

var obj = [{ a: 1 }, { b: 2 }, { c: 3 }];
    var result = obj.reduce((obj, item) => [item.key] = item.value);
    console.log(result);

but i'm always getting : 但我总是得到:

Uncaught TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined 未捕获的TypeError:无法读取未定义的属性'Symbol(Symbol.iterator)'

I searched a lot, but the examples didn't help me... i think that's something simple, but after 1 hour, i'm nothing getting . 我搜索了很多,但这些例子并没有帮助我...我认为这很简单,但1小时后,我什么都没有。

What i want.. 我想要的是..

[{a: 1}, {b: 2}, {c: 3}] to {a: 1, b: 2, c: 3}

You could use Object.assign and spread syntax ... . 你可以使用Object.assign传播语法...

 var obj = [{ a: 1 }, { b: 2 }, { c: 3 }]; console.log(Object.assign({}, ...obj)); 

With Array#reduce 使用Array#reduce

 var obj = [{ a: 1 }, { b: 2 }, { c: 3 }]; console.log(obj.reduce((r, o) => Object.assign(r, o), {})); 

Without Object.assign 没有Object.assign

 var obj = [{ a: 1 }, { b: 2 }, { c: 3 }]; console.log(obj.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = v), r), {})); 

ES5 ES5

 var obj = [{ a: 1 }, { b: 2 }, { c: 3 }]; console.log(obj.reduce(function (r, o) { Object.keys(o).forEach(function (k) { r[k] = o[k]; }); return r; }, {})); 

If you want to use reduce: 如果你想使用reduce:

var arr = [{ a: 1 }, { b: 2 }, { c: 3 }];

var result = arr.reduce((obj, item) => Object.assign(obj, item), {});

Check the MDN documentation when in doubt. 如有疑问,请查看MDN文档

you can do it in the following way using reduce 您可以使用reduce以下列方式执行此操作

 var obj = [{ a: 1 }, { b: 2 }, { c: 3 }]; var result = obj.reduce((obj, item) => { Object.assign(obj, item) return obj; }, {}); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM