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