Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement