What is the most effective method for locating and updating an object within an array using JavaScript?

I have a list of products structured like this:

var itemsList = [
    {   
        id: 'as5',
        name: 'Coca-Cola',
        price: 17.5,
        unit: 'Bottles',
        quantity: 23
    },
    {   
        id: 'q7s',  
        name: 'Cheese',
        price: 34.8,
        unit: 'Kilos',
        quantity: 6
    },
    {   
        id: 'pa5',
        name: 'Bread',
        price: 3.5,
        unit: 'Pieces',
        quantity: 100
    },
    {   
        id: 'capu2',
        name: 'Oil',
        price: 21,
        unit: 'Bottle',
        quantity: 10
    },
    {   
        id: 'bon4',
        name: 'Bonafont Water',
        price: 25,
        unit: 'Jug',
        quantity: 12
    },
    {   
        id: 'tun1',
        name: 'Tuna',
        price: 11,
        unit: 'Can',
        quantity: 30
    },                              
];    

I want to locate an item by its ID and decrease the quantity by one.

This is my current approach using lodash 3.10:

var item = _.find(itemsList, {id: 'tun1'});
item.quantity--;
itemsList.splice(_.findIndex(itemsList, {id: 'tun1'}), 1, item);

However, I find this method inefficient as it requires multiple operations and iteration with splice.

Could someone suggest a more optimized solution in plain ES5 JS?

Answer №1

You were so close! To make it even more concise, you can simplify the last line like this:

Decrease quantity of product with id 'tun1' by one:
_.find(productsList, {id: 'tun1'}).quantity--;

Answer №2

Skipping the final step is futile. Your grasp on Javascript references appears to be lacking.

reduceQuantity(product.item);

This accomplishes your goal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The handlebar does not undergo any modifications once the authentication process is completed

This file is named header.hbs <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{{ title }}</title> ...

The sweetalert 2 input field is unresponsive or disabled within a materializecss modal, making it impossible to type in

My modal includes a SweetAlert2 popup when I click the "add bills" button. The code for this feature is from their documentation, so I don't believe the issue lies there. However, I am experiencing a problem where the input field is not type-able and ...

Clicking outside of Bootstrap Modal inputs causes them to lose focus

Currently, I am tackling a challenge involving 2 bootstrap modals located on the same page with Bootstrap version 2.3.2. A frustrating issue that has arisen is that whenever either modal appears, the first time you click on any of the inputs within the mo ...

Executing asynchronous functions within a loop using useEffect

My current scenario is as follows: export default function Component({ navigation }) { const [ item, setItem ] = useState([]); useEffect(() => { AsyncStorage.getItem('someItem') .then(data => JSON.parse(data)) ...

Create a new array containing the keys from an array of objects

My task involves extracting the key puppies from an array of objects and returning it in a new array: The input is an array of dogs structured like this: [ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof&ap ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Trigger a modal popup upon page load event generated from the server side using C#

I am trying to display a modal popup based on certain conditions during the page load event, but I am facing some issues. This is my modalPopup code: <script type="text/javascript"> function openModal(message, header, url) { $('#my ...

Using Framework7 and AngularJS to efficiently load pages

When creating a phone application using phonegap, AngularJS, and Framework7, I encountered an issue with the page swapping functionality of Framework7. The problem arises because Framework7 injects new HTML pages into the DOM dynamically when a user click ...

What is the best way to display the value of an option in an HTML element

I would like to include an h2 element that displays an updated price based on the selected option value. Below is my current code snippet: <select name="price"> <option value="2799"> 1-6 installments</opt ...

'this' in Arrow functions does not have a reference to the calling context

Something seems off about the context in this code. I've left comments to describe my issue below: const cat = { //arrow function meow: () => { console.log(this); }, makeMeow(){ // Why does 'this' refer ...

What is the best way to initialize firebase with context in a React application?

Currently, I'm following a tutorial at this link: I've hit a roadblock at the following step: Context.jsx import React from 'react'; const FirebaseContext = React.createContext(null); export default FirebaseContext; index.js impo ...

What is the best way to instruct Vite to exclude specific files within a directory from the build process?

After initializing a fresh Vue application with the command npm create vue, I implemented a functionality where the app fetches a configuration at runtime and extracts a component name from it. These dynamic components reside in a directory called "pluggab ...

Encountering an error when attempting to generate a production build after running the npm install command with the

After adding the brotli-webpack-plugin as a devDependency, I encountered an issue when attempting to generate a production build using npm run build (which internally runs next build). The error message displayed was: Error: Cannot find module 'bro ...

Error message: The Next.js GraphQL-Yoga server is returning a 404 error on the

I am brand new to using graphql-yoga 3 in conjunction with next js for creating APIs with GraphQL. Unfortunately, my routes at /api/graphql are returning a 404 error even though I have followed the example provided here. The default page loads fine, but I ...

Implement a commenting feature upon the button being clicked

When a button is clicked, I want to insert some HTML code onto my page. Here's the code that I wish to add: <form action="#" id="Reactie_form"> <input id="Form_voornaam" type="text" placehol ...

Retrieve your username data using Ajax

I'm working on a JSP page with the following structure: https://i.sstatic.net/3aFoz.png In updating the table in my database, I've added a new username column that accepts any string of text. Once the 'update user' button is clicked, ...

Breaking down a javascript project

As the trend of splitting large JavaScript projects into separate files and then compiling them into a single distribution increases, I am eager to explore this workflow. While I have considered Node.js, npm, and Grunt for this purpose, I find the learning ...

"Upon submitting a form in React JS, the components will automatically trigger a

Within my application, there is a Mobx storage in conjunction with a modal window component. The form within the modal window allows me to collect all the properties and push them into an array named 'cart' within the storage as an object. Take a ...

Is there a simple angular directive available for displaying expandable/collapsible text?

I have been exploring the idea of creating an Angular directive that would truncate a paragraph or a div if it exceeds a certain number of characters (for example, 115). I have not been successful in finding a solution that fits my needs. I have come acro ...

Tips for displaying the Material UI Menu component on the left side instead of the default right side

Recently, I created a dropdown component using Material UI's Menu component. However, the default behavior of the menu is to open towards the right side. I actually need it to open towards the left instead. I attempted to modify its styling, and whil ...