Akshdeep Singh
Akshdeep Singh

Reputation: 1447

How to change values of keys of an object having same value without mutation while keeping reference of unchanged keys the same in javascript?

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.


EDIT

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

Answers (1)

Nina Scholz
Nina Scholz

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

Related Questions