更新数组中的所有元素

updating all elments in an array

我必须使用 Immutablejs 更新数组中的所有元素

JSON 看起来像这样:

imState = Immutable.fromJS({
  app: {
    line: {
      name: "Bar Chart",
      series: [
        {
          name: "Series1x",
          color: "#82ca9d"
        },
        {
          name: "Series2x",
          color: "#2239ca"
        },
        {
          name: "Series3x",
          color: "#c2a5ca"
        }
      ]
    }
  }
})

我只想遍历所有系列元素并将颜色更改为固定颜色“#1bf115”。

我猜您会使用 update 函数。这个函数没有API文档,所以我一直在做很多尝试错误。

我试过这样使用它:

imState = imState.update(
  ['app', 'line', 'series'],
  series => series.map(s => s.update('color', color => "#1bf115"))
)

但是我在 series.map.

处收到未定义的错误

为什么这是错误的?

因为您提供的是深度嵌套路径,所以请使用 updateIn.

而不是 update
imState = imState.updateIn(
  ['app', 'line', 'series'],
  series => series.map(s => s.update('color', color => "#1bf115"))
)