Reputation: 1999
Basically I have an array of objects. Each object has an array which I need to change the values.
I'm using React, so this is a state:
[
{
"points": [
60,
5,
60,
20,
70,
20,
70,
15
],
"finished": true,
"color": "#6292C6"
},
{
"points": [
80,
15,
80,
25,
90,
25
],
"finished": true,
"color": "#3FD971"
},
{
"cultureName": "",
"points": [],
"finished": false
}
]
What's the best way to change the points
values of this state? I need to multiply them by a factor (4.96).
Upvotes: 1
Views: 144
Reputation: 21297
map
your array, spread
each object inside it overwriting only the property points
(map
multiplying each item by the factor 4.96
)
const data = [{id: 1, points: [1,2,3]}, {id: 2, points: []}]
const changedData = data.map(item =>({
...item,
points : item.points.map(value => value * 4.96)
}))
console.log(changedData)
Upvotes: 12
Reputation: 1413
Use nested maps
const myData = [
{"points": [60,5,60,20,70,20,70,15],"finished": true,"color": "#6292C6"},
{"points": [80,15,80,25,90,25],"finished": true,"color": "#3FD971"},
{"cultureName": "","points": [],"finished": false}
]
const newArray = myData.map(elm=>{
const points = elm.points.map(point=> point*4.96)
return {...elm , points}
})
console.log(newArray)
Upvotes: 2
Reputation: 317
const factor = 4.96
const arrayOfObject = [] // .. here your array of objects
const modifiedArrayOfObjects = arrayOfObject.map( stats => {
const newPoints = stats.points.map(point => point * factor)
stats.points = newPoints
return stats
}
Here I make a new array of objects, where I map each object to one, where each point has been multiplied by your factor.
Upvotes: 1