Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert arrays to key value pair

I have an array

[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]

is it possible to become key value pair?

{
"flight1" : "123",
"flight2" : "456"
}
like image 714
muhnizar Avatar asked May 04 '17 09:05

muhnizar


2 Answers

You can use reduce() and return object as result.

var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}]

var result = arr.reduce(function(r, e) {
  r[e.field] = e.value;
  return r;
}, {});

console.log(result)
like image 129
Nenad Vracar Avatar answered Oct 09 '22 15:10

Nenad Vracar


You could map the key value pair and assign it to an object.

var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
    result = Object.assign(...data.map(a => ({ [a.field]: a.value })));

console.log(result);
like image 3
Nina Scholz Avatar answered Oct 09 '22 15:10

Nina Scholz