scriobh
scriobh

Reputation: 890

Create array from the values that are looped in for...in

I was getting this weird result when I'm trying to construct an array of objects by using for...in loop for a object

const obj = {
  name: 'John',
  age: '25'
}
for (const property in obj) {
  const obj1 = {
    prop1: property,
    prop2: obj[property]
  }
  const result = [].push(obj)
  console.log(result)
}
I was expecting the result to be

[{prop1: 'name', prop2: 'John'}, {prop1: 'age', prop2: '25'}]

Could anyone please help?

Upvotes: 0

Views: 43

Answers (2)

StackSlave
StackSlave

Reputation: 10627

You are pushing to a new Array that is scoped inside of your loop. You really want to do:

const obj = {
  name: 'John',
  age: '25'
}
const results = [];
for(let p in obj){
  results.push({
    prop1: p,
    prop2: obj[p]
  });
}
console.log(results)

Upvotes: 0

Aplet123
Aplet123

Reputation: 35482

push returns the new length of the array, which is why you see 1. Move the array initialization out of the loop and log after the loop is finished:

const obj = {
  name: 'John',
  age: '25'
}
const result = []
for (const property in obj) {
  const obj1 = {
    prop1: property,
    prop2: obj[property]
  }
  result.push(obj1)
}
console.log(result)

Upvotes: 3

Related Questions