Substitute a section of an item with something else

I am faced with a situation where I have a collection of objects, each containing multiple key-value pairs.

There will be numerous instances where various API calls or server-sent events (via websockets) will provide updated data for some objects in the collection. The challenge lies in the fact that each call only returns specific parts of the data for each object, rather than the entire set of information.

The main question here is how to efficiently update only the modified bits, considering that this data is utilized in a React application and we need to take into account immutability implications as well.

My initial approach involves matching the id from the original data with the new data, followed by looping through the incoming data to identify the keys and updating the original data accordingly. However, there might be a more effective method to achieve this.

let original_data = [{
    id: 1,
    value_1: 'will only change when value_1 method is called for id=1',
    value_2: 'will only change when value_2 method is called',
  },
  {
    id: 2,
    value_1: 'will only change when value_1 method is called for id=2',
    value_2: 'will only change when value_2 method is called',
  },
]

let replacement_data = [{
  id: 1,
  value_1: 'assume value_1 method was called for id=1',
}]

for (let i in replacement_data) {
  //get the index matched by id
  index = original_data.findIndex((x => x.id === replacement_data[i].id))

  //replace only the data that has changed
  for (var key in replacement_data[i]) {
    original_data[index][key] = replacement_data[i][key]
  }
}

console.log(original_data);

Although the current method works, I am concerned about its performance if faced with an event where thousands of such changes occur. Are there any potential optimizations or best practices that could improve this process?

Answer №1

To enhance performance, consider including a comparison using JSON.stringify to determine if the objects differ (this method relies on the assumption that keys are in the same order).

let initial_dataset = [
  {
    id:1,
    value_1:'will only change when value_1 method is called for id=1',
    value_2:'will only change when value_2 method is called',
  },
  {
    id:2,
    value_1:'will only change when value_1 method is called for id=2',
    value_2:'will only change when value_2 method is called',
  },
];

let updated_dataset = [
  {
    id:1,
    value_1:'assume value_1 method was called for id=1',
  },
  {
    id:2,
    value_2:'assume value_2 method was called for id=2',
  }
];


const applyChanges = () => {
    updated_dataset.forEach((item) => {
        const data = initial_dataset.find(x => x.id === item.id);
        if (JSON.stringify(data) !== JSON.stringify(item)){ 
           for (const key in item){
             data[key] = item[key];
           }
        }
    });
}

applyChanges();

console.log(initial_dataset);

Answer №2

If you have a list of objects with unique IDs, you can create a reference object based on those IDs to easily update specific values without the need for array iteration.

const
    update = data => {
        const references = Object.fromEntries(objects.map(obj => [obj.id, obj]));
        return (id, key, value) => references[id][key] = value;
    };
    objects = [{ id: 1, attribute_1: 'value for attribute_1 at ID=1', attribute_2: 'value for attribute_2' }, { id: 2, attribute_1: 'value for attribute_1 at ID=2', attribute_2: 'value for attribute_2' }],
    updateData = update(objects);

updateData(1, 'attribute_2', 'new value');

console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Utilizing key-value pairs in ES6, one can leverage the Map() documentation to access various operations effortlessly. It may require some data adjustments or a loop creation to populate the map.

let original_data = new Map();
original_data.set(1, {
    id: 1,
    value_1: 'will only change when value_1 method is called for id=1',
    value_2: 'will only change when value_2 method is called',
  });
original_data.set(2, {
    id: 2,
    value_1: 'will only change when value_1 method is called for id=2',
    value_2: 'will only change when value_2 method is called',
  });

Simply utilize Map.set to update specific data:

let replacement_data = [{
  id: 1,
  value_1: 'assume value_1 method was called for id=1',
}];
for(const data of replacement_data){
  original_data.set(data.id, data);
}

Answer №4

In my opinion, using Object.assign could be a suitable approach

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

What is the process for updating the label on the leaflet control layers toggle?

I have incorporated mapbox and leaflet into my website, and I'm looking to modify the label "Satellite" in leaflet-control-layers-toggle to "SAT". Is there a way to achieve this change using leaflet? https://i.sstatic.net/DAR9m.png ...

A step-by-step guide on validating two password fields using Joi in TypeScript React

I have created a versatile form component using TypeScript called AbstractForm. This component is intended to be inherited by other components such as LoginForm, RegisterForm, and so on. Currently, I am working on a component named DerivedForm. The validat ...

Modify iframe form action URL dynamically upon user visiting the URL with a specified parameter

Below you will find a code example: The page URL is: <html> <body> <h1>main page</h1> <iframe src="http://example2.com"> <form id="test" action="http://example3.com?id=1"> ... </form&g ...

Display the razor page in a modal dialog box

I want to display a razor page within a modal dialog: Here is the code for the razor page: <div class="container"> <div class="title modal " tabindex="-1" id="loginModal" data-keyboard="false" data-backdrop="static"> < ...

Explain the function of the "js" method in gulp when working with a Typescript project and gulp-typescript

In the midst of outlining a seed node.js based server project for Typescript using Gulp and Mocha, I came across an example at: https://www.typescriptlang.org/docs/handbook/gulp.html. The gulpfile provided contains the following code snippet: var gulp = ...

The Dynamic Duo: setTimeout with a Sidekick Named V

After installing V8 standalone and running javascript code using the command ./d8 source.js, I encountered an issue with setTimeout resulting in a ReferenceError: setTimeout is not defined. Is this expected behavior? Is there a way to include this functi ...

Do hidden fields require postback in order to function?

I'm curious if a hidden field must have a postback in order to send or access its value on the server side. For example, let's say we have a hidden field named x that is set to a value in JavaScript on the client side. Can we access this field in ...

Unable to assign attribute following discovery

Can the attribute of an anchor element that is found using find() be set? I attempted this: $(this).children('a').setAttribute("href","a link"); Although it does locate the anchor element, why am I receiving an error when trying to use setAttr ...

Enhancing user experience by tailoring rewrites in Next.js according to the user-agent

I am working on a NextJs multi-domain website and need to fetch data based on the domain and device type. While I am able to identify the domain, I am looking to extract the user-agent in rewrite rules and utilize it within the getStaticProps function. Bel ...

In my sequence of Promises, a "reject is not defined" error led to the rejection of a Promise

In my code, I set up a chain of Promises like this: let promise = new Promise((resolve, reject) => { imgToDisplay.onload = () => { resolve(imgToDisplay.width); } }) .then((result) => { window.URL.revokeObjectURL(imgToD ...

Oops! Looks like there was an issue during the testing process with Postman

Encountering an issue during the API testing using Postman with error messages like "something went wrong" authRoute.js In the authRoute file, I have implemented the application logic. I need assistance in resolving the error. Additionally, I have attach ...

JavaScript embedded within LD-JSON format

Is it feasible to run JavaScript code within an ld+json script? Like for instance, "window.location.hostname" <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "http://" + window.location.ho ...

What are some tactics for avoiding movement in the presence of a border setting?

I created a webpage that has the following structure: .topbar-container { width: 100%; position: fixed; top: 0; background-color: #2d3e50; z-index: 999; display: flex; transition: height 500ms; } @media (min-width: 992px) { .topbar-cont ...

Ways to programmatically compare all elements between two separate arrays

Is there a way to create a process where the first loop iterates through the elements of one array, while another loop goes through a second array and compares each element in the first array with all elements in the second array? For example: //first loo ...

What is the best way to enhance search results in PHP by refining or filtering data from a MySQL

I am currently in the process of developing my website and could use some assistance. Right now, my web page allows users to search for product information and returns relevant results based on their query. While this works well when users search through k ...

Separate terms & mix / scramble characters

I am attempting to rearrange words by shuffling the letters within each word. Instead of shuffling the letters within the first word with its own letters, it is currently shuffling the first word with the second word's letters. My goal is to split th ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

Instructions on extracting the initial 16 bytes of data from a base64 decoded string

Looking to extract the first 16 bytes of data from a Base64Decode string. Here is my code snippet, seeking suggestions on how to achieve this: let base64Encodeded = "Hf8Qqpr1klv+Mjle4v0yfOXbQpiXwICyEDF4bYGt/ve7h9a1cEqd5z3QpvnPMLzRpDxSBEutaOdh8SN/Yi9 ...

Enhance your AngularJS application with advanced security features and implement a local storage

I have implemented an AngularJS application that utilizes angular ui-router for routing. Despite my efforts to enhance security, I encountered some challenges: To manage user authentication, I store tokens and user roles in local storage, redirecting ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...