muhnizar
muhnizar

Reputation: 327

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"
}

Upvotes: 9

Views: 22213

Answers (5)

fafl
fafl

Reputation: 7387

The new Map() constructor can do this for you:

var data = [
    {"field": "flight1", "value": "123"},
    {"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));

If you're not familiar with Map objects, they work almost exactly the same as plain objects, except they are a little easier to iterate over, and have a .size property.

But if you prefer to have a plain object, you can get one this way:

var result = Object.fromEntries(data.map(obj => [obj.field, obj.value]));

Upvotes: 5

Josh D.
Josh D.

Reputation: 333

This might help someone another day. I tried all the examples above, but each time the console was giving me something like this: { flight1: "123", flight2: "456" }

My problem was that I was converting a serialized array way to soon which resulted in lots of tiny problems. Below was the code that didn't work:

var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);

Note that flight1 and flight2 lost their double quotes. Below was my solution:

var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);

NB: This was a code for submitting user information to a database (neDB) using the electron framework

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

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

Upvotes: 3

BenG
BenG

Reputation: 15164

you could use a standard for loop:-

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

var obj = {};

for (var i = 0; i < data.length; i++)
    obj[data[i].field] = data[i].value;

console.log(obj);

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122145

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)

Upvotes: 22

Related Questions