user5554873
user5554873

Reputation: 11

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 = {
      v1 : 'k1',
      v2 : 'k2',
      v3 : 'k3'
    }

    a =[];

Object.entries(obj).forEach(
  ([key, value]) => {
    a.push({key : value});
  });
console.log(a);

This is my expected output:

[{v1 : 'k1'}, {v2 : 'k2'}, {v3 : 'k3'}]

Upvotes: 1

Views: 1506

Answers (3)

adiga
adiga

Reputation: 35222

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

Upvotes: 2

Andy
Andy

Reputation: 63524

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

Upvotes: 1

aseferov
aseferov

Reputation: 6393

var obj =  { v1 : 'k1', v2 : 'k2', v3 : 'k3' }

var result = []
for(var i in obj) result.push([i, obj[i]])


console.log(result)

Upvotes: 1

Related Questions