1

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

3 Answers 3

12

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)

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

Comments

2

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)

Comments

1
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.

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.