Reputation: 1447
I have an object like this:
const obj1 = {key1: value1, key2: value2, key3: value1}
I want to change the value of all keys having value value1
to value3
:
// obj2
{key1: value3, key2: value2, key3: value3}
Basically, my values are another objects.
I do not want to create new instances of the unchanged values.
And, I do not want to mutate the original object obj1
.
My reason is that keeping the reference same would prevent me unnecessary re-renders.
see this tweet for details
I don't know how to give example on this, all I can say is that, if the value of the key has to be changed, return new value, otherwise return old value, do not assign old value.
Upvotes: 3
Views: 1174
Reputation: 386644
You could get the entries, look for the wanted value and replace this value. Then build a new object.
const
source = { key1: 1, key2: 2, key3: 1 },
search = 1,
replace = 3,
target = Object.fromEntries(Object
.entries(source)
.map(([k, v]) => [k, v === search ? replace : v])
);
console.log(target);
Upvotes: 3