Update very deep object with spread operator

spread operator deep copy
spread operator update array of objects
spread operator clone object
redux reducer spread operator
redux nested state
js deep copy with spread
clone deep vs spread
es6 deep copy objects

I've got an object that looks like this:

  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" }
      }
    }
  }

I've got a for loop that change the children "show" property to the opposite boolean. So I try to update the value with this but doesn't worked.

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

            }
          }

"appClassId" variable is a variable that I get from the action.

How can I update every key in the child property for instance state.1.children.1.show

With the help of @markerikson author of:

http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html

I was able to update that deep level of nested data:

The object to update are the all objects under "children" property of this object:

 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" }
      }
    }
  }

And the code to update it is:

let newState = {};
newState = { ...state, newState }

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

Using Object Spread Operator, often find yourself using Object.assign() to create copies of objects with new or updated values. An alternative approach is to use the object spread syntax recently added to the JavaScript specification. The object spread operator is conceptually similar to the ES6 array spread operator. for deep cloning objects. To be precise, only Chrome 58 at the moment supports the object spread operator, behind a flag too. But I’ve been using it with great satisfaction with Babel behind. It’s very expressive, and also helps adopting an immutable pattern in your code, as opposed to Object.assign it creates a new object every time.

I would recommend leaning on a utility library like lodash.js in addition to the spread operator if you're doing anything more complex than assigning a value or two.

Assuming that the number of appClassIds inside state and children inside each appClass are completely dynamic:

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
    }
  }
}, {})

Hope this helps!

Spread Operator Tricks - DEV Community ‍ ‍ , Some handy tips, tricks, patterns to use with the spread operator. handy patterns using the spread operator so I thought I'd write up a quick blog post sharing some. The spread operator does not preform a deep clone of a nested object. Copying an object and simultaneously updating properties. Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

try this:

const originalChildren = state[appClassId].children;
let updatedChildren = {};

for (var child in originalChildren) {
   if (originalChildren.hasOwnProperty(child)) {
      updatedChildren = {
        ...updatedChildren,
        [child]: { ...originalChildren[child], show: !originalChildren[child].show }
      };
   }
}

const newState = {
  ...state,
  [appClassId]: {
    ...state[appClassId],
    children: { ...originalChildren, ...updatedChildren }
  }
}

How to update nested props in reducer? · Issue #432 · reduxjs/redux , My reducers are getting very, very lengthy going multiple levels deep. Updating nested object without entity ids to denormalize #2065 Second, while the Array Spread operator is part of ES6, the Object Spread operator is  #Note on Object Spread Operator Like the Array Spread Operator, the Object Spread Operator creates a shallow clone of the original object. In other words, for multidimensional source objects, elements in the copied object at a depth greater than one are mere references to the source object (with the exception of primitives , which are copied).

Another example,

let test = [
  { id: 1, name: 'Phone',
    Devices: [
      { id: 1, name: 'BlackBerry',GroupId: 1 },
      { id: 2, name: 'Iphone', GroupId: 1 }
    ]
  }, { id: 2, name: 'Speaker',
    Devices: [
      { id: 3, name: 'Senheiser', GroupId: 2 },
      { id: 4, name: 'Simbadda', GroupId: 2 }
    ]
  }
];

const GroupId = 1;
const device = {
  id: 5,
  name: 'Android',
  GroupId: GroupId
}


let Group = [...test];

const idx = test.findIndex(payload => {
  return payload.id === GroupId
});

console.log(Group[idx].Devices = [...Group[idx].Devices, device]);

Hope it will help

Spread Operator, Using spread operator and Object.assign is one way of practicing… Case 2: Let us have nested “person” object as below, So, it starts iterating from index 1. Redux: Update an Object in an Object (This isn’t specific to Redux – the same method applies with plain React state. See here for how to adapt it.) When the object you want to update is one (or more) levels deep within the Redux state, you need to make a copy of every level up to and including the object you want to update. Here’s an example one level deep:

Deeply Nested Objects and Redux, In very simple terms, the React rendering process is sensitive only to the With deeply nested objects, the workload (of both human and machine) For a property update of a deeply nested object to be rendered, the Note: It is important to know the benefits and pitfalls of using the spread operator. Second, while the Array Spread operator is part of ES6, the Object Spread operator is still a Stage 3 proposal, and is not yet a final part of the language. The syntax can be enabled if you're using Babel by adding the appropriate compiler plugin. For TypeScript, I think that was just added in TypeScript 2.1. 👍

Using Spread operator to update the state in react, Hi, does copying nested object using spread have different address (reference). We do that so react can know while rendering the dom that  When performing a deep copy, those external objects are copied as well, so the new, cloned object is completely independent from the old one. Searching how to deep clone an object in JavaScript on the internet, you’ll find lots of answers but the answers are not always correct. Easiest option: use Lodash

Spread syntax, Spread syntax allows an iterable such as an array expression or string For object literals (new in ECMAScript 2018): Note: Spread syntax effectively goes one level deep while copying an array. Update compatibility data on GitHub created an account, you will be prompted to do so after signing in. This article guides through object spread and rest syntax. Including how object spread implements recipes like object cloning, merging, properties overriding and more. What follows is a short recap on enumerable properties, and how to distinguish own from inherited properties. These are necessary basics to understand how object spread and rest

Comments