Home > Software engineering >  Restructure an array of objects in JS so key and value pairs match
Restructure an array of objects in JS so key and value pairs match

Time:02-26

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'
  }
]

CodePudding user response:

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);

  • Related