簡體   English   中英

將對象數組轉換為對象對象並分配特定鍵

[英]Convert array of objects to object of objects and assign specific keys

我知道有很多關於這個的問題,但我找不到我想要的。

我有一個像這樣的對象數組

[{id:1}, {id:2}]

我想將 id 指定為鍵,將對象指定為值

{
    "1": {
         id: 1
     },
     "2": {
         id: 2
     }
}

使用Array.reduce()根據key參數創建一個帶有鍵的對象:

 const keyBy = (arr, key) => arr.reduce((r, o) => { r[o[key]] = o; return r; }, {}); const arr = [{id:1}, {id:2}]; const result = keyBy(arr, 'id'); console.log(result);

如果您希望它更實用,請使用object spread替換累加器:

 const keyBy = (arr, key) => arr.reduce((r, o) => ({ ...r, [o[key]]: o }), {}); const arr = [{id:1}, {id:2}]; const result = keyBy(arr, 'id'); console.log(result);

使用.reduce

 const input = [{id:1}, {id:2}]; const output = input.reduce((accum, { id }) => { accum[id] = { id }; return accum; }, {}); console.log(output);

一種方法可能是(es6):

const newObject = {};
myArrayWithObjects.map(singleObject => {
    newObject[singleObject.id.toString()] = singleObject;
    return true;
});

Lodash還可以幫助您解決這個問題:

const newObject = _.keyBy(myArrayWithObjects, function(singleObject) {
    return singleObject.id.toString();
});

https://github.com/paularmstrong/normalizr絕對是更糟糕的一瞥。 但我想,對於這項任務來說,這太過分了。

暫無
暫無

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

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