How to Find and Update Object in Javascript Array?


Share This Post

Learn how to work with arrays and objects if you want to become a Javascript developer. You must become proficient at manipulating the things included in arrays.

Fortunately, we can assist you. Continue reading to learn about our issue and various approaches to solving it.

The Problem – Find and Update Object in Array

Let’s say we have a list of objects:

var inventory = [{item: 'shirt', quantity: 10}, {item: 'pants', quantity: 4}]

In this array, we wish to locate a certain object and change its quantity. And we don’t want to transfer the full array to a new variable to do this.

We can use the findIndex function to look up the index of the item we require since, at the most fundamental level, all we are working with is an array.


The Solution – findIndex

It is straightforward to use findIndex. The code is provided, along with a breakdown:

var itemIndex = inventory.findIndex(x => x.item == 'shirt')

var item = inventory[itemIndex]
item.quantity = 2

inventory[itemIndex] = item

We use findIndex on the array in the first line to look for the desired item. In this instance, it’s a “shirt,” but in a real-world situation, it would be some kind of distinctive identification.

The object’s index location within our array is returned as the return value. Now, as seen in lines two and three, we can extract that object into a variable and change whatever field we like. In line 4, we finally insert our new object into the initial array.

Using the spread operator when writing back to the array will allow us to condense this approach even more.

var itemIndex = inventory.findIndex(x => x.item == 'shirt')

inventory[itemIndex] = {...inventory[itemIndex], quantity: 2}

You can see from the example above that we didn’t write the changed object to a variable first, instead writing it directly to the array.

This answer is succinct and straightforward, but it presupposes that you are looking for an item in your array that has a special identification.

You must use a loop to carry out your action if the array contains repeat objects. Here’s an illustration:

inventory.forEach(x, index) => {
  if(x.item == 'shirt') {
    inventory[index] = {...x, quantity: 2}



Please enter your comment!
Please enter your name here

Related Posts

How to Choose Best Lift Chair?

For people with physical disabilities and the elderly, getting...

NuWave Brio Air Fryer Review

Craving for some fried goods but scared of the...

Commercial Toaster: Top Picks with Buying Guide and FAQs

Commercial Toaster: Top Picks with Buying Guide and FAQs...

Best High-Velocity Blower Fans

Does your room feel so warm during the summer?...

10 Best Xbox One Gaming Chair: Buying Guide And Reviews

For some people, console gaming should have the right...

Best Gaming Chairs Under 200$

Whether you game as a hobby or happen to...
- Advertisement -spot_img