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

查看:109
本文介绍了JavaScript - 如何遍历对象数组以创建一个新对象,其键是原始对象的初始键/值对的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况:

我必须实现一个函数mapById,当给定一个对象数组时,它返回一个对象,其中键是输入对象的id和值是相应的输入对象。

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.

var input = [{id: 102, name: "Alice"},
             {id: 205, name: "Bob", title: "Dr."},
             {id: 592, name: "Claire", age: 32}];

console.log(mapById(input));

应该给出以下结果:

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 } }

我该如何解决这个问题?如果这是一个数组我可以使用'推'方法。对象有类似的方法吗?我需要关闭吗?我知道这是基本的东西,但我对javascript很新。

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.

谢谢。

推荐答案

你实际上非常接近:

function mapById(list) {
    var obj = {};
    list.forEach(function(item) {
        obj[item.id] = item;
    });
    return obj;
}

我怎么做:

 const result = Object.assign(...input.map(el => ({[el.id] : el})));

这篇关于JavaScript - 如何遍历对象数组以创建一个新对象,其键是原始对象的初始键/值对的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆