Amy
Amy

Reputation: 59

push array's value to object's value

I have a question about the array and object conversion. I have an array which has three values. if my object has already had its key, how do I put the array value to the object by for loop?

If I use for loop like below, every value is engineer.

let arr= ['john', 29, 'engineer']
let obj = {}
for (let i = 0; i < arr.length; i++) {
    obj.name = arr[i]
    obj.age = arr[i]
    obj.job = arr[i]
}

console.log(obj)

The result of above code:

{
  name: 'engineer',
  age: 'engineer',
  job: 'engineer'
}

Instead, I want the following result:

{
  name: 'john',
  age: 29,
  job: 'engineer'
}

Upvotes: 2

Views: 49

Answers (1)

Unmitigated
Unmitigated

Reputation: 89214

You can use array destructuring.

let arr = ['john', 29, 'engineer'];
const [name, age, job] = arr;
let obj = {name,age,job};
console.log(obj);

You can refer to the indexes using bracket notation as well, if all the values will always be at the same position.

let arr= ['john', 29, 'engineer']
let obj = {
    name: arr[0],
    age: arr[1],
    job: arr[2]
};

console.log(obj);

Upvotes: 4

Related Questions