Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array into key / value pairs

I have pushed different values from nested loops into an object, resulting in something like this:

obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];

But I'd like it to return like this:

obj = [{"blue": 1}, {"red": 4}, {"yellow": 2}, {"green": 7}];

Do I have to manually build that syntax or is there a quicker way?

like image 875
Kirk Ross Avatar asked Feb 03 '17 05:02

Kirk Ross


1 Answers

Use a simple for loop.

var obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];

var res = [];

for (var i = 0; i < obj.length; i += 2) {
  var o = {};
  o[obj[i]] = obj[i + 1];
  res.push(o);
}

console.log(res);

An ES6 solution using Array.from() method.

let obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];

console.log(Array.from({ length: obj.length / 2 }, (_, i) => ({ [obj[2 * i]]: obj[2 * i + 1] })));
like image 155
Pranav C Balan Avatar answered Oct 05 '22 23:10

Pranav C Balan