Search code examples
javascriptobjectjavascript-objectskey-value

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}]


Solution

  • 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;}