简体   繁体   中英

how to loop and convert an array of objects to an object with key value pair

I have an Array of Objects something like this

[
  {name: "John", country: "USA", revision: 1},
  {name: "Mark", country: "England", revision: 0},
  {name: "Bruce", country: "France", revision: 1}
]

I want to convert it into an object with key value pair with name key, like this

{
  John : {name: "John", country: "USA", revision: 1},
  Mark : {name: "Mark", country: "England", revision: 0},
  Bruce : {name: "Bruce", country: "France", revision: 1}
}

This is what I have done but it does not seems to work

let component = contents.reduce(((content, current}) => {
    content[name] = current;
    return content;
}), {});

This can be done using Array.prototype.reduce func.

 const input = [ {name: "John", country: "USA", revision: 1}, {name: "Mark", country: "England", revision: 0}, {name: "Bruce", country: "France", revision: 1} ]; const output = input.reduce((acc, {name, ...item}) => { acc[name] = item; return acc; }, {}); console.log(output);

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