簡體   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

這是我的情況:

我必須實現一個函數“mapById”,當給定一個對象數組時,它返回一個對象,其中鍵是輸入對象的id,值是相應的輸入對象。

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}

這是我迄今為止的功能:

function mapById(list) {
    var obj = {};
    var objectKey = '';
    list.forEach(function(item) {
        objectKey = (Object.values(item)[0]);
        var obj = {[objectKey]: item};
    });
    return obj;
}

我可以為原始數組中的每個對象獲取一個新的鍵/值對,但我無法弄清楚如何將每個新的鍵/值對添加到新對象。

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很新。

謝謝。

你其實非常接近:

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

使用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
}, {})

reduce函數允許您在迭代數組時構建單個對象。 注意最后一個參數{} ,它將m初始化為空對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM