0

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?

0

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.