Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array of key–value objects to array of objects with a single property?

I have an array of objects like this:

[
  { "key": "fruit", "value": "apple" },
  { "key": "color", "value": "red" },
  { "key": "location", "value": "garden" }
]

I need to convert it to the following format:

[
  { "fruit": "apple" },
  { "color": "red" },
  { "location": "garden" }
]

How can this be done using JavaScript?

like image 500
Binson Eldhose Avatar asked Dec 08 '25 00:12

Binson Eldhose


2 Answers

You can use .map

var data = [
  {"key":"fruit","value":"apple"},
  {"key":"color","value":"red"},
  {"key":"location","value":"garden"}
];

var result = data.map(function (e) {
  var element = {};
  element[e.key] = e.value;
  
  return element;
});

console.log(result);

also if you use ES2015 you can do it like this

var result = data.map((e) => {
   return {[e.key]: e.value};
});

Example

like image 133
Oleksandr T. Avatar answered Dec 10 '25 13:12

Oleksandr T.


Using an arrow function, with the data called arr

arr.map(e => {
    var o = {};
    o[e.key] = e.value;
    return o;
});

This generates a new Array and does not modify the original

It can be simplified down to one line as

arr.map(e => ({[e.key]: e.value}));

If you can't assume arrow function support yet, you would write this longhand

arr.map(function (e) {
    var o = {};
    o[e.key] = e.value;
    return o;
});
like image 26
Paul S. Avatar answered Dec 10 '25 12:12

Paul S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!