Thursday, May 23, 2024
82
rated 0 times [  84] [ 2]  / answers: 1 / hits: 115354  / 9 Years ago, mon, december 21, 2015, 12:00:00

I am using Redux. In my reducer I'm trying to remove a property from an object like this:



const state = {
a: '1',
b: '2',
c: {
x: '42',
y: '43'
},
}


And I want to have something like this without having to mutate the original state:



const newState = {
a: '1',
b: '2',
c: {
x: '42',
},
}


I tried:



let newState = Object.assign({}, state);
delete newState.c.y


but for some reasons, it deletes the property from both states.



Could help me to do that?


More From » immutability

 Answers
10

How about using destructuring assignment syntax?





const original = {
foo: 'bar',
stack: 'overflow',
};

// If the name of the property to remove is constant
const { stack, ...withoutFirst } = original;
console.log(withoutFirst); // Will be { foo: bar }

// If the name of the property to remove is from a variable
const key = 'stack'
const { [key]: value, ...withoutSecond } = original;
console.log(withoutSecond); // Will be { foo: bar }

// To do a deep removal with property names from variables
const deep = {
foo: 'bar',
c: {
x: 1,
y: 2
}
};

const parentKey = 'c';
const childKey = 'y';
// Remove the 'c' element from original
const { [parentKey]: parentValue, ...noChild } = deep;
// Remove the 'y' from the 'c' element
const { [childKey]: removedValue, ...childWithout } = parentValue;
// Merge back together
const withoutThird = { ...noChild, [parentKey]: childWithout };
console.log(withoutThird); // Will be { foo: bar, c: { x: 1 } }




[#63987] Saturday, December 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margob

Total Points: 302
Total Questions: 89
Total Answers: 100

Location: Guadeloupe
Member since Sat, Jul 25, 2020
4 Years ago
;