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
}
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)
您需要将获得的当前对象传播为:
const newArr = arr.map(i => ({ ...i, power: 2 }));
You want to do this, you are spreading arr
and should be spreading the array getting passed to map
(eg i
):
const newArr = arr.map(i => {
const r = {
...i,
power:2
}
return r
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.