Reputation: 25
I've been a few days trying to get my head around Redux to be used with my Reactjs project. I'm working on a reducer and trying to add a nested property into state. To do this, I'm using spread operator at different levels. The problem is that initially the state slice this reducer manages is empty and therefore I run into the following problem... taking this as an example of what I'm trying to do:
var foo = {}; // Initially the state slice is an empty object.
var bar = {...foo,
1: {
...foo[1],
2: {
...foo[1][2],
baz: 100 // New property I'm trying to add.
}
}
};
console.log(bar);
(property keys 1 and 2 are two variables provided to the reducer in my actual app)
I you run the above piece of code it will yield en error saying Cannot read property '2' of undefined
at line ...foo[1][2],
. Alright, foo[1][2]
is not defined yet, but how am I supposed to accomplish this? Maybe I'm missing something very basic...
Upvotes: 0
Views: 77
Reputation: 633
something like that works for your example but it seems pretty hacky.
bar = {
...foo,
1: {
...foo[1] ? foo[1] : {},
2: {
...foo[1] && foo[1][2] ? foo[1][2] : {},
baz: 100 // New property I'm trying to add.
}
}
}
Upvotes: 1