简体   繁体   中英

Assign keys to an array of objects

Let's say I have the following array: [{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 ?

[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

If you want to have specific properties (based on id ), then the output should better be a plain object, and not an array.

In that case you can use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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