0

I want to rewrite an array and to get a new one at the final. This is my code:

const arr = [
  {
    type:"Fiat", model:"500", color:"white"
  },
  {
    type:"ford", model:"5300", color:"gray"
  }
];
const newArr = arr.map(i => {
    const r = {
      ...arr,
      power:2
    }
    return r
})



console.log(newArr)

Now i get the wrong result, because one every iteration, the new array grow with a copy of the first array:

 const r = {
    ...arr,
    power:2
 }

How to get the next result?

{
  type:"Fiat", model:"500", color:"white", power: 2
},
{
  type:"ford", model:"5300", color:"gray", power: 2
}

3 Answers 3

2

You are spreading arr .You need to spread i which is the object inside the array.

const arr = [
  {
    type:"Fiat", model:"500", color:"white"
  },
  {
    type:"ford", model:"5300", color:"gray"
  }
];
const newArr = arr.map(i => {
    const r = {
      ...i,
      power:2
    }
    return r;
})
console.log(newArr)

With array function you can implicitly

const arr = [
  {
    type:"Fiat", model:"500", color:"white"
  },
  {
    type:"ford", model:"5300", color:"gray"
  }
];
const newArr = arr.map(i => ({...i, power: 2}));
console.log(newArr)

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

Comments

2

You need to spread the current object that you are getting as:

const newArr = arr.map(i => ({ ...i, power: 2 }));

Comments

1

You want to do this, you are spreading arr and should be spreading the array getting passed to map (e.g. i):

const newArr = arr.map(i => {
    const r = {
      ...i,
      power:2
    }
    return r
})

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.