[英]Using reduce to get object with objects
I have array of the following form:我有以下形式的数组:
[
{key: "key1", value: value1}
{key: "key2", value: value2}
{key: "key3", value: value3}
...
]
I need to convert to the following form:我需要转换为以下形式:
{ { key1 : value1}, { key2 : value2}, { key3 : value3} }
How to do it with reduce() ?如何用reduce()做到这一点?
I am trying to use this code:我正在尝试使用此代码:
var someObject = this.someArray.reduce(function(acc, item) {
return { [item.key]: item.value};
}, {});
but I always get only the last item instead of all of them.但我总是只得到最后一项而不是全部。
The issue is in your return问题在于你的回报
return acc + { [item.key]: item.value};
You cannot use the +
operator to add
objects.您不能使用+
运算符来add
对象。 Try the following:尝试以下操作:
acc[item.key] = item.value;
return acc
This assumes your keys
are all unique.这假设您的keys
都是唯一的。 See full example below:请参阅下面的完整示例:
let x = [{ key: "key1", value: 'value1' }, { key: "key2", value: 'value2' }, { key: "key3", value: 'value3' }, ].reduce((accumulatedValue, curentValue) => { accumulatedValue[curentValue.key] = curentValue.value; return accumulatedValue }, {}) console.log(x);
Either you seek an array of object, then the following example applies:要么你寻找一个 object 的数组,那么下面的例子适用:
const res = [{ key: 'key1', value: 'value1', }, { key: 'key1', value: 'value1', }, { key: 'key1', value: 'value1', }].reduce((tmp, { key, value, }) => [...tmp, { [key]: value, }, ], []); console.log(res);
Either you seek an unique object, then the following example applies:要么您寻求一个独特的 object,然后以下示例适用:
const res = [{ key: 'key1', value: 'value1', }, { key: 'key2', value: 'value2', }, { key: 'key3', value: 'value3', }].reduce((tmp, { key, value, }) => ({...tmp, [key]: value, }), {}); console.log(res);
About your code, as people told you already in the comments, you cannot simply use the +
operator to concatenate either arrays or objects.关于您的代码,正如人们在评论中已经告诉您的那样,您不能简单地使用+
运算符连接 arrays 或对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.