繁体   English   中英

如何更改对象数组中数组中的每个值?

[英]How to change each value from an array inside an array of objects?

基本上我有一个对象数组。 每个 object 都有一个我需要更改值的数组。

我正在使用 React,所以这是一个 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
  }
]

更改此 state 的points值的最佳方法是什么? 我需要将它们乘以一个因子(4.96)。

map您的数组,在其中spread每个 object 仅覆盖属性pointsmap将每个项目乘以因子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)

使用嵌套地图

 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)

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
}

在这里,我创建了一个新的对象数组,其中我将 map 每个 object 设置为一个,其中每个点都乘以您的因子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM