简体   繁体   English

JavaScript - 如何遍历对象数组以创建一个新对象,其键是原始对象的初始键/值对的值

[英]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.

相关问题 如何在javascript中迭代对象作为键值对 - How to iterate through object as key value pair in javascript 如何在javascript中向数组添加新对象(键值对)? - How to add a new object (key-value pair) to an array in javascript? 根据键值对将对象数组连接成新的 object - Concatenate Array of Objects into a new object depending on a key value pair 迭代对象的对象并在每个对象中插入键值对 - Iterate over an Object of objects and insert key value pair in each object 遍历javascript对象并动态添加对象属性(JS对象中的键值对) - Iterate through javascript object and add object properties dynamically (key-value pair in JS object) 如何从数组的键值对创建一个新数组? - How to create a new array from array's key value pair? 遍历对象并通过javascript中的键查找值 - Iterate through an object and find value by key in javascript 如何将单个键值对对象转换为具有键值对的对象数组? - How to convert a single key value pair object to array of objects with key value pair? 如何将 object 键值对以数组为值转换为键值对的多个对象? - How to convert object key value pair with array as values to multi objects of key value pair? 如何循环并将对象数组转换为具有键值对的对象 - how to loop and convert an array of objects to an object with key value pair
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM