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