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?
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] })));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With