Javascript Object With Key Value Pairs, How To Separate Each Pair As Individual Object?
I have a javascript object with key value pairs i want to separate each pair as individual object and push it to a array how do i do that? var obj = new Object(); obj = { v
Solution 1:
You have almost got it. To create a dynamic property from a variable (it's called Computed property names), you need to add []
around key
. Otherwise, it just creates an object with just "key" as the key
:
Object.entries(obj).forEach(([key, value]) => {
a.push({ [key] : value });
// ↑↑
});
or, much simpler using map
:
const obj = {v1:'k1',v2:'k2',v3:'k3'},
a = Object.entries(obj).map(([key, value]) => ({[key] : value}));
console.log(a);
Solution 2:
var obj = { v1 : 'k1', v2 : 'k2', v3 : 'k3' }
var result = []
for(var i in obj) result.push([i, obj[i]])
console.log(result)
Solution 3:
A more functional way to approach this would be to map
over the object entries to produce a new array of objects.
var obj = { v1 : 'k1', v2 : 'k2', v3 : 'k3' }
const out = Object.entries(obj).map(([k, v]) => ({ [k]: v }));
console.log(out);
Post a Comment for "Javascript Object With Key Value Pairs, How To Separate Each Pair As Individual Object?"