Reputation: 890
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)
}
[{prop1: 'name', prop2: 'John'}, {prop1: 'age', prop2: '25'}]
Could anyone please help?
Upvotes: 0
Views: 43
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
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