issue with spread operator in javascript

AskMen :

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
}
Maheer Ali :

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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=319805&siteId=1