ajith kumar
ajith kumar

Reputation: 361

key value in the object is not populating correctly

I am trying to store each property of the object into an Object array.

Ex :

{
  a: b,
  c: d
}

to

[
  { a: b }, 
  { c: d }
]

Below is the code which I am trying to execute.

var a = {
  a: "a",
  b: "b"
}

var newA = []

for (var keys in a) {
  if (a.hasOwnProperty(keys)) {
    newA.push({
      keys: a[keys]
    })
  }
}

console.log(newA)

When i am pushing the property to the "newA" array the key value is pushed as "keys" instead of the original key name.

Result: [{keys: a},{keys:b}]

Expected: [{a:a},{b:b}]

Upvotes: 2

Views: 112

Answers (2)

Shidersz
Shidersz

Reputation: 17190

You need to use computed property names . Also I believe hasOwnProperty() is redundant in your code, at least for this particular example, where your object doesn't inherit enumerable properties. Look at the for ... in description. So you can go with:

for (const key in a)
{
    newA.push({[key] : a[key]});
}

However, as an alternative you can use Object.entries() and Array.map():

var a = {a : "a", b : "b"};

let res = Object.entries(a).map(([k,v]) => ({[k]: v}));

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Upvotes: 4

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Use Computed property names by placing brackets around the variable keys within your push statement:

newA.push({ [keys]: a[keys] })

Example in action:

var a = {
  a: "a",
  b: "b"
}

var newA = []

for (var keys in a) {
  if (a.hasOwnProperty(keys)) {
    newA.push({
      [keys]: a[keys]
    })
  }
}

console.log(newA)

Upvotes: 3

Related Questions