简体   繁体   中英

Restructure an array of objects in JS so key and value pairs match

I have an array with objects like this

[ 
  {name: 'Donegal', code: 'DL'}, 
  {name: 'Dublin', code: 'DUB'}, 
  {name: 'Meath', code: 'MH'}
]

How do I restructure it so it looks like this

[ 
  {Donegal: 'Donegal'}, 
  {Dublin: 'Dublin'}, 
  {Meath: 'Meath'}
]

**** EDIT ****

Apologies, but after receiving feedback, I looked at my question again and realized that I wrote the desired object incorrectly, apologies for that. Regardless, the question has been answered (Thank you everyone for your comments and answers). For the record, here is the desired output

[ 
  {
    Donegal: 'Donegal', 
    Dublin: 'Dublin', 
    Meath: 'Meath'
  }
]

The structure you are targeting looks wrong: having an array with little objects that have one dynamic property, kills any benefit you would have from using object keys.

Instead go for one object (not an array):

 let input = [ {name: 'Donegal', code: 'DL'}, {name: 'Dublin', code: 'DUB'}, {name: 'Meath', code: 'MH'} ]; let output = Object.fromEntries( input.map(({name}) => [name, name]) ); 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