简体   繁体   English

将键分配给对象数组

[英]Assign keys to an array of objects

Let's say I have the following array: [{id: 1, name: "john"}, {id: 2, name: "doe"}]假设我有以下数组: [{id: 1, name: "john"}, {id: 2, name: "doe"}]

How can I assign the id value of each object as a key and convert it to something like bellow ?如何将每个对象的 id 值分配为键并将其转换为类似于 bellow 的值?

[1:{id: 1, name: "john"}, 2:{id: 2, name: "doe"}]

I did something like this myArray.map((t) => {return {[t.id]: {t}}}) but obviously my result is nested in an object我做了这样的事情myArray.map((t) => {return {[t.id]: {t}}})但显然我的结果嵌套在一个对象中

If you want to have specific properties (based on id ), then the output should better be a plain object, and not an array.如果你想拥有特定的属性(基于id ),那么输出最好是一个普通对象,而不是一个数组。

In that case you can use Object.fromEntries :在这种情况下,您可以使用Object.fromEntries

 let data = [{id: 1, name: "john"}, {id: 2, name: "doe"}]; let result = Object.fromEntries(data.map(o => [o.id, o])); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM