Modifying Objects in an Array in Javascript

·

2 min read

A way to check and modify if necessary each property in each object in an array

Imagine you have an array of objects like this

myArray = [
{'name':'2', 'address':'Manchester','pet':'cat'},
{'shirt':'5', 'chair':'34', 'carpet':'youtube'},
{'plus':'1', 'time':'some', 'wire':'question'}
]

...and you want to update the array of objects so that only the property values that consist of one digit, are changed to something else.

This is a good place to make use of the Object.entries function. This built in ES6 function takes an object and breaks it into an array or key/value pair arrays, so for instance

Object.entries({'name':'2', 'address':'Manchester','pet':'cat'})

becomes

 [
["name", "2"],
 ["address", "Manchester"],
["pet", "cat"]
]

...this makes it easy for us to then loop through the properties just as you would any other array.

We can also after deconstructing the object, put it back together again by using Object.fromEntries eg

Object.fromEntries( [
["name", "2"],
 ["address", "Manchester"],
["pet", "cat"]
])

becomes

{name: "2", address: "Manchester", pet: "cat"}

knowing we have these two powerful functions we can combine them like this;

 Object.fromEntries(Object.entries(
{name: "2", address: "Manchester", pet: "cat"}
))

gives

{name: "2", address: "Manchester", pet: "cat"}

Remember back at the start I wanted to step through each item in myArray? I'm going to use a simple forEach loop to do this.

Then once I have hold of the item - which is an object - I will use Object.entries to enable me to step through this object's properties - because we are now dealing with an array of arrays, any of the Array methods are available for us to use.

I choose map

This will map a new set of arrays with the values modified as necessary (using a callback to convertDigitValues(value))

Then Object.fromEntries rebuilds the newly mapped object.

This newly mapped object is now pushed to the array called updatedProperties.

    let updatedProperties = [];
    myArray.forEach((propertyObject)=>{
      const objectWithDigitsChanged = Object.fromEntries(
      Object.entries(propertyObject) 
      .map(([ key, val ]) => [ key,  this.convertDigitValues(val)])
      )
      updatedProperties.push(objectWithDigitsChanged)
    });

So this is a way that you can access each object in an array of objects and check and update their properties.