Update value in object javascript

Updating JavaScript Object Property

Let’s say you have an array of objects and you want to create a function that will update each object in that array.

And let’s say you’ve written this code:

 const object1 = < property1: "Value 1" >; const object2 = < property2: "Value 2" >; const listOfObjects = [object1, object2]; const copyOfListOfObjects = [. listOfObjects]; function updateObjects(objects) < return objects.map((object) => < Object.keys(object).forEach((property) =>< object[property] = "Updated value"; >); return object; >); > const listOfUpdatedObjects = updateObjects(listOfObjects); console.log(listOfObjects); console.log(copyOfListOfObjects); console.log(listOfUpdatedObjects); 

What will be the output of console.log(listOfObjects); statement?

From the first look listOfObjects should have two objects: < property1: "Value 1" >and < property2: "Value 2" >, because we didn’t change listOfObjects — we passed it to updateObjects function as an argument and then returned a new list of updated objects using .map() function.

Remember that .map() returns a brand new array.

So it looks like listOfObjects should not be changed.

What will be the output of console.log(copyOfListOfObjects); statement?

It’s a copy of listOfObjects and we didn’t do anything else with copyOfListOfObjects , so it’s easy to assume that it should have two objects < property1: "Value 1" >and < property2: "Value 2" >, just like listOfObjects does.

What will be the output of console.log(listOfUpdatedObjects); statement?

Now that’s a result of calling updateObjects function and passing listOfObjects to it, so it should have two objects with updated values: < property1: "Updated value" >and < property2: "Updated value" >, correct?

If you run the code, you might be surprised to find out that all three console.log statements output updated two objects: < property1: "Updated value" >and < property2: "Updated value" >.

Let’s go through that code once more time and think carefully about what it does.

First we declare two objects:

 const object1 = < property1: "Value 1" >; const object2 = < property2: "Value 2" >; 

Not only we declare two objects < property1: "Value 1" >and < property2: "Value 2" >, but we also assign them to object1 and object2 constants.

What value do we exactly assign to object1 and object2 ? In JavaScript, we don’t assign objects. We assign references to those objects. In other words, object1 stores a reference to an object < property1: "Value 1" >and object2 stores a reference to an object < property2: "Value 2" >.

This is important to understand.

Then we create two lists — listOfObjects and copyOfListOfObjects :

 const object1 = < property1: "Value 1" >; const object2 = < property2: "Value 2" >; const listOfObjects = [object1, object2]; const copyOfListOfObjects = [. listOfObjects]; 

listOfObjects is made of object1 and object2 . It’s not made of < property1: "Value 1" >and < property2: "Value 2" >. It’s made of references to < property1: "Value 1" >and < property2: "Value 2" >.

Then we create a copy of listOfObjects : [. listOfObjects] and we call it copyOfListOfObjects . What exactly are we copying here? We’re not copying objects < property1: "Value 1" >and < property2: "Value 2" >. Instead, we’re copying references to < property1: "Value 1" >and < property2: "Value 2" >.

Now listOfObjects stores two references to two objects and copyOfListOfObjects stores another two references to exactly the same two objects.

This matters: we copied references, but they all point to the same objects. We didn’t copy the objects themselves.

Then we called updateObjects function and passed listOfObjects as an argument to that function. And we’ve assigned the return value to listOfUpdatedObjects :

 const object1 = < property1: "Value 1" >; const object2 = < property2: "Value 2" >; const listOfObjects = [object1, object2]; const copyOfListOfObjects = [. listOfObjects]; function updateObjects(objects) < return objects.map((object) => < Object.keys(object).forEach((property) =>< object[property] = "Updated value"; >); return object; >); > const listOfUpdatedObjects = updateObjects(listOfObjects); 

What exactly have we passed to updateObjects function as an argument? A list of references to two objects: < property1: "Value 1" >and < property2: "Value 2" >.

 function updateObjects(objects) < return objects.map((object) => < Object.keys(object).forEach((property) =>< object[property] = "Updated value"; >); return object; >); > 

It iterates over objects and for each object it iterates over each property of that object and updates its value to Updated value .

The only caveat here is that updateObjects function doesn’t iterate objects. It iterates references to objects.

Let’s refactor that function and introduce better names:

 function updateObjects(referencesToObjects) < return referencesToObjects.map((referenceToObject) => < Object.keys(referenceToObject).forEach((property) =>< referenceToObject[property] = "Updated value"; >); return referenceToObject; >); > 

Now it’s clearer what the function does. However, there’s one line where it actually changes the object’s property: referenceToObject[property] = «Updated value»;

When you see a line of code like this — this should raise a red flag in your mind.

Think about what it does. It takes one of the references to an object and then it uses that reference to get access to the actual value stored inside of that object. And then it updates the existing value with a new value — «Updated value» .

In other words — it mutates the original object that we’ve declared at the very beginning of our code.

Think about this: you can have many references to one object, as we do in our example. We have multiple references to < property1: "Value 1" >object. All those references point to the same object. And when we take one of those references and use it to accesses values inside of our object and update those values — all other references will now point to that updated object. And you might not be aware of this and assume that other references still point to the previous version of that object with original values.

Do not mutate objects. Because when you do that, no other reference knows about the fact that the object has changed. This will create bugs in your code.

Instead of mutating existing objects — create new objects.

Let’s improve our updateObjects function:

 function updateObjects(objects) < return objects.map((object) =>< const newObject = ; Object.keys(newObject).map((property) => < newObject[property] = "Updated value"; >); return newObject; >); > 

The solution is to copy object : const newObject = <. object>; and then update value of a copy: newObject[property] = «Updated value»; and return that copy return newObject; . The original object remains unchanged.

Now when you run this code, the first two console statements will output two lists that are made of < property1: "Value 1" >and < property2: "Value 2" >objects and the third console statement will output a list made of < property1: "Updated value" >and < property2: "Updated value" >.

Conclusion

Avoid object[property] = «Updated value»; code whenever possible. Instead create a copy and update that copy. Do not mutate objects.

Источник

Update value in object javascript

Last updated: Jan 10, 2023
Reading time · 4 min

banner

# Update all the Values in an Object in JavaScript

To update all the values in an object:

  1. Use the Object.keys() method to get an array of the object’s keys.
  2. Iterate over the array using the forEach() method and update each value.
  3. After the last iteration, all the values in the object will be updated.
Copied!
const obj = country: 'Chile', city: 'Santiago', address: 'Example', name: 'bobby hadz', >; Object.keys(obj).forEach(key => obj[key] = ''; >); // 👇️ console.log(obj);

update all values in object

We used the Object.keys method to get an array of the object’s keys.

Copied!
const obj = country: 'Chile', city: 'Santiago', address: 'Example', name: 'bobby hadz', >; // 👇️ [ 'country', 'city', 'address', 'name' ] console.log(Object.keys(obj));

The next step is to iterate over the array of keys using the Array.forEach method.

The function we passed to the forEach() method gets called for each element of the array and gets passed 3 arguments:

If you need to use the index, assign the second parameter of the callback function to a variable.

Copied!
const obj = country: 'Chile', city: 'Santiago', address: 'Example', >; Object.keys(obj).forEach((key, index) => obj[key] = obj[key] + index; >); // 👇️ console.log(obj);

# Conditionally update the values in an object

You can also check for a condition in an if statement before updating the object’s values.

Copied!
const obj = name: 'bobby hadz', num1: 9, num2: 19, num3: 29, >; Object.keys(obj).forEach((key, index) => if (typeof obj[key] === 'number' && obj[key] > 10) obj[key] = 0; > >); // 👇️ console.log(obj);

conditionally update the values in an object

The code sample checks if each key has a value of type number and if the value is greater than 10 .

If both conditions are met, the key’s value gets set to 0 .

We used the logical (&&) operator to check if multiple conditions are true , but you can also check for a single condition.

You can also use the Object.entries() method instead of Object.keys() .

Copied!
const obj = name: 'bobby hadz', num1: 9, num2: 19, num3: 29, >; Object.entries(obj).forEach(([key, value], index) => if (typeof obj[key] === 'number' && value > 10) obj[key] = 0; > >); // 👇️ console.log(obj);

The Object.entries method returns an array of the given object’s key-value pairs.

Copied!
const obj = name: 'bobby hadz', num1: 9, num2: 19, num3: 29, >; // [ // [ 'name', 'bobby hadz' ], // [ 'num1', 9 ], // [ 'num2', 19 ], // [ 'num3', 29 ] // ] console.log(Object.entries(obj));

The first element in each array is the key and the second is the value.

# Update all the Values in an Object without Mutation

This is a three-step process:

  1. Use the Object.keys() method to get an array of the object’s keys.
  2. Use the reduce() method to iterate over the array.
  3. On each iteration, return a new object that contains the values from the previous iteration and the updated value.
Copied!
const obj = country: 'Chile', city: 'Santiago', address: 'Example', name: 'bobby hadz', >; const newObj = Object.keys(obj).reduce((accumulator, key) => return . accumulator, [key]: ''>; >, >); // console.log(newObj); // // country: 'Chile', // city: 'Santiago', // address: 'Example', // name: 'bobby hadz' // > console.log(obj);

update all values in object without mutation

We got an array of the object’s keys using the Object.keys() method.

The function we passed to the Array.reduce method gets called for each element in the array.

We initialized the accumulator variable to an empty object because that’s what we passed as the second argument to the reduce() method.

On each iteration, we use the spread syntax (. ) to unpack the key-value pairs of the object into a new object and update the current value.

The value we return from the callback function gets passed as the accumulator on the next iteration.

This approach doesn’t change the values of the original object, it returns a new object.

# Conditionally update the values in an object using reduce()

You can also conditionally update the values in an object using reduce() .

Copied!
const obj = name: 'bobby hadz', num1: 9, num2: 19, num3: 29, >; const newObj = Object.keys(obj).reduce((accumulator, key) => if (typeof key[obj] === 'number' && key[obj] > 10) return . accumulator, [key]: 0>; > return . accumulator, [key]: obj[key]>; >, >); // 👇️ console.log(newObj);

conditionally update the values in an object using reduce

If the current key is a number and is greater than 10 , we set it to 0 .

Otherwise, we return the key as is.

# Update all the Values in an Object using for. of

This is a three-step process:

  1. Use the Object.keys() method to get an array of the object’s keys.
  2. Use a for. of loop to iterate over the array.
  3. Update the value of each key.
Copied!
const obj = country: 'Chile', city: 'Santiago', address: 'Example', name: 'bobby hadz', >; for (const key of Object.keys(obj)) obj[key] = ''; > // 👇️ console.log(obj);

update all values in an object using for of

The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .

On each iteration, we set the value of the current key to an empty string.

This approach mutates the original object.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Язык php является языком программирования
Оцените статью