[英]JavaScript — how to iterate through an array of objects to create a new object whose key is the value of the original object's initial key/value pair
Here is my situation: 这是我的情况:
I have to implement a function "mapById", which, when given an array of objects, returns an object, where the keys are the ids of the input objects and the values are the corresponding input objects. 我必须实现一个函数“mapById”,当给定一个对象数组时,它返回一个对象,其中键是输入对象的id,值是相应的输入对象。
var input = [{id: 102, name: "Alice"},
{id: 205, name: "Bob", title: "Dr."},
{id: 592, name: "Claire", age: 32}];
console.log(mapById(input));
should give the result below: 应该给出以下结果:
102: {id: 102, name: "Alice"},
205: {id: 205, name: "Bob", title: "Dr."},
592: {id: 592, name: "Claire", age: 32}
Here is my function thus far: 这是我迄今为止的功能:
function mapById(list) {
var obj = {};
var objectKey = '';
list.forEach(function(item) {
objectKey = (Object.values(item)[0]);
var obj = {[objectKey]: item};
});
return obj;
}
I can get a new key/value pair for each object in the original array but I can't figure out how to add each new key/value pair to the new object. 我可以为原始数组中的每个对象获取一个新的键/值对,但我无法弄清楚如何将每个新的键/值对添加到新对象。
ObjectKey: 102
item: { id: 102, name: 'Alice' }
obj: { '102': { id: 102, name: 'Alice' } }
ObjectKey: 205
item: { id: 205, name: 'Bob', title: 'Dr.' }
obj: { '205': { id: 205, name: 'Bob', title: 'Dr.' } }
ObjectKey: 592
item: { id: 592, name: 'Claire', age: 32 }
obj: { '592': { id: 592, name: 'Claire', age: 32 } }
How can i fix this? 我怎样才能解决这个问题? If this was an array I could use the 'push' method.
如果这是一个数组我可以使用'推'方法。 Is there a similar method for objects?
对象有类似的方法吗? Do I need a closure?
我需要关闭吗? I know this is basic stuff but I'm quite new to javascript.
我知道这是基本的东西,但我对javascript很新。
Thanks. 谢谢。
You are actually quite close: 你其实非常接近:
function mapById(list) {
var obj = {};
list.forEach(function(item) {
obj[item.id] = item;
});
return obj;
}
How i would do that: 我该怎么做:
const result = Object.assign(...input.map(el => ({[el.id] : el})));
Use Array.prototype.reduce() : 使用Array.prototype.reduce() :
var input = [{id: 102, name: "Alice"}, {id: 205, name: "Bob", title: "Dr."}, {id: 592, name: "Claire", age: 32}] var output = input.reduce(function(accumulator, item) { accumulator[item.id] = item return accumulator }, {}) console.log(output)
var output = input.reduce(function(m,x,i) {
m[x.id] = x
return m
}, {})
The reduce
function allows you to build a single object as you iterate an array. reduce
函数允许您在迭代数组时构建单个对象。 Notice the last parameter {}
which initialises m
to an empty object. 注意最后一个参数
{}
,它将m
初始化为空对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.