使用扩展运算符更新非常深的对象

Die*_*nue 5 javascript reactjs spread-syntax redux react-redux

我有一个看起来像这样的对象:

  state: {
    "1": {
      "show": false,
      "description": "one",
      "children": {
        "1": { "show": false, "description": "one" },
        "2": { "show": false, "description": "one" }
      }
    },
    "2": {
      "show": false,
      "description": "one",
      "children": {
        "1": { "show": false, "description": "one" },
        "2": { "show": false, "description": "one" }
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

我有一个 for 循环,可以将子项“show”属性更改为相反的布尔值。所以我尝试用这个来更新值,但没有成功。

      for (var childKey in state[appClassId].children) {
        newState = {
          ...state,
          [appClassId]: {
            children: {
              [childKey]: { ...state[appClassId].children[childKey], show: !state[appClassId].children[childKey].show}

            }
          }
Run Code Online (Sandbox Code Playgroud)

“appClassId”变量是我从操作中获取的变量。

如何更新子属性中的每个键,例如 state.1.children.1.show

jak*_*kee 0

如果您正在做比分配一两个值更复杂的事情,我建议您除了扩展运算符之外还依赖实用程序库。lodash.js

假设每个内部和内部的appClassIds数量完全是动态的:statechildrenappClass

import { reduce } from 'lodash'

const newState = reduce(state, (modifiedState, appClass, appClassId) => {
  const { children } = appClass
  // toggle show for each child (non-mutating)
  const toggledChildren = reduce(children, (newChildren, child, childId) => {
    return {
      ...newChildren,
      [childId]: { ...child, show: !child.show }
    }
  }, {})

  // persist modified children within the appClass
  return {
    ...modifiedState,
    [appClassId]: {
      ...appClass,
      children: toggledChildren
    }
  }
}, {})
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!