2

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

1 Answer 1

4

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);

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

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.