Switch out an item within a list of objects with a different item

I have a variable called this.rows that contains a collection of items. There is a real-time item being received from the server, which matches one of the items in the this.rows object collection.

How can I replace an item with new values?

Below is an example:


    let rows = [
        {id: 11, active: 'no'},
        {id: 22, active: 'yes'},
        {id: 33, active: 'no'},
        {id: 44, active: 'no'}
    ]

    new_item = {id: 22, active:'yeah'};

    rows.forEach(item => {
        if (item.id === new_item.id) {
          return new_item;
        }
    });

Answer №1

Utilize the "findIndex" function to locate the index of the new item element within the rows array. Then, validate if a match was found (by checking if the index is greater than -1). Set the new item in the array at the position of the located element.

const indexOfItemInArray = rows.findIndex(q => q.id === new_item.id);

if (indexOfItemInArray > -1) {
   rows[indexOfItemInArray] = new_item;
}

Alternatively, you can use the "splice" method:

const indexOfItemInArray = rows.findIndex(q => q.id === new_item.id);
rows.splice(indexOfItemInArray, 1, new_item);

Answer №2

If you want to efficiently update an array by replacing a value for a specific id, the map function is your best friend:

items = items.map((item) => {
    if (item.id === updated_item.id) {
        item = updated_item;
    }

    return item;
});

Answer №3

search for an item within rows and update its keys:

modify rows:

_.chain(rows)
    .find({ id: new_item.id })
    .assign(new_item)
    .value();

avoid modifying rows directly:

const updatedRows = _.chain(rows)
    .findIndex({ id: new_item.id })
    .thru(index => _.chain(rows)
        .cloneDeep()
        .set(index, new_item)
        .value()
    )
    .value();

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

Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this: <div class="form-group {{dateStatus.class}}"> <p class="input-g ...

Trigger an event on an element upon first click, with the condition that the event will only fire again if a different element is clicked

Imagine having 5 span elements, each with an event listener like ` $('.option1').on("click", function(){ option1() }) The event for option 1 is also the default event that occurs on page load. So if no other options are clicked, you won&apo ...

What steps should I take to enable this SimpleModal to load automatically?

Is there a way to have the SimpleModal script load when the page loads instead of having to click a button? Thank you for your help! < div id='basic-modal' > <a href='#' class='basic'>Demo</a> </div> ...

Failed to convert value to a string

I'm dealing with a frustrating issue and I just can't seem to figure it out. The error message I'm getting is Cast to string failed for value "{}" at path "post". { "confirmation": "fail", "message": { "message": "Cast to string fai ...

Looking for Precise Matching within JSON Using JavaScript

I've been experimenting with creating a form that submits data and then checks it against a JSON array to see if there's a matching object already present. Here is a snippet of my JSON data for reference: [ { "ASIN":"B0971Y6PQ3 ...

"Enhancing the edit functionality of *.Vue components within Laravel: A comprehensive guide

I am new to Vue and seeking some assistance. I have a Laravel code integrated with Vue, and I am trying to make changes to the navbar.vue component. However, whenever I add or remove something and save it, there is no update reflected in the HTML of the ...

Effective ways to check for the time discrepancy between dates in moment.js

My server is set to use UTC date format and I am running my node server in UTC as well. I am looking to determine if the current time in Indian timezone (which is +5.30) is greater than 8AM, and if so, send an email notification. How can I achieve this u ...

What is the best way to save characters from different languages into variables?

I created an application that reads words from a TXT file and stores them in a database. The issue arises when I encounter words from other languages that contain non-English characters, resulting in the following problem: Is it possible to store these ch ...

How can you prevent videos from constantly reloading when the same source is used in multiple components or pages?

How can we enhance loading performance in Javascript, React, or Next JS when utilizing the same video resource across various components on different pages of the website to prevent unnecessary reloading? Is there a method to store loaded videos in memor ...

How to avoid console messages when dealing with Axios 422 error handling?

When developing my application, I decided to use Laravel for the backend and Vue for the frontend. To handle validation errors, I chose to implement code 422 based on recommendations from this article. The PHP code snippet in my RegisterController: if ($t ...

Evaluating the conditional rendering of a React child component using Jest and Enzyme

I am currently working on expanding the test coverage for this particular file: import React, { useContext } from 'react'; import UserContext from '../../contexts/user'; import styles from './index-styles.scss'; const UserLog ...

Error in React JS: SyntaxError - "Unexpected token '?'"

Following the guidelines on this website, I successfully set up a new reactJS application, proceeded to run npm i && npm run dev and encountered the following error message: /home/www/node_modules/next/dist/cli/next-dev.js:362 showAll ...

I am puzzled as to why my Details Modal keeps appearing whenever I click anywhere, even when I have specifically added it to only show up on the event of today. Additionally, I am encountering

ERROR Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref at coerceRef (http://localhost:3000/static/js/bundle.js:59386:21) at createChil ...

Having trouble with Window.open on Mobile Devices and Canvas?

I've created a unique "button" within the div element. This button is designed to detect user interaction, such as clicks or taps, and when triggered, it should open a new window with the URL: "http://www.google.com". However, while this functionality ...

How do I set up middleware with async/await in NestJS?

I am currently integrating bull-arena into my NestJS application. export class AppModule { configure(consumer: MiddlewareConsumer) { const queues = this.createArenaQueues(); const arena = Arena({ queues }, { disableListen: true }); consumer. ...

What is the best way to initially conceal content and then reveal it only after an ajax call is made?

Currently, I have a situation where content is revealed after the callback function of a .js library (typed.js) executes. Here is the script I am using: Javascript $(function(){ $("#logo-black").typed({ strings: ["Nothing^450&Co^250.^500" ...

Error 500: Issue with JQuery AJAX File Upload

Hey there, I'm facing an issue with doing a file upload using JQuery's AJAX feature as I keep getting the error 500. $(function() { $( 'form' ).submit ( function() { $.ajax({ type: &a ...

Vue allows you to use regular expressions with arrays

Looking to implement a list filtering system using checkboxes. This is how I am looping through an array from VUEX: <div class="checkbox" v-for="brand in brands" :key="brand.id"> <input name="brands" typ ...

What is causing my Javascript media query for the sidebar to not function properly?

I am working on implementing a sidebar that slides out 250px using JavaScript on the desktop view. However, I want the sidebar to take up 100% width when viewed on mobile devices. Despite my attempts to use Media Queries in JavaScript to achieve this, I am ...

Different ways to showcase a value from the CSS file on the console using console.log

In this guide, you can learn how to create a custom directive in Angular by following this tutorial: Custom Directive Tutorial. The directive should function as intended. Still, I want to see the color value set in the CSS file displayed on the console us ...