Refresh a collection of objects with a new set of objects

Is there a way to update an array of objects with values from another array of objects?

Consider these two arrays:

const originalArray = [
  {id:'a',html:'',user:''},
  {id:'b',html:'',user:''},
  {id:'c',html:'',user:''},
];

const newArray = [
  {id:'a',html:'',user:''},
  {id:'b',html:'',user:''},
  {id:'c',html:'',user:''},
  {id:'d',html:'<p>Hello World</p>',user:'TEST USER'},
  {id:'e',html:'<p>Hello World TWO</p>',user:'TEST USER TWO'},
];

I am looking to merge the new values from newArray into originalArray.

The expected result should be:

[
  {id:'a',html:'<p>Hello World</p>',user:'TEST USER'},
  {id:'b',html:'<p>Hello World TWO</p>',user:'TEST USER TWO'},
  {id:'c',html:'',user:''},
];

Answer №1

Suppose you wish for objects with matching IDs to be updated, here is my approach:

  1. Establish an object named byId that maps IDs to corresponding objects.
  2. Iterate through the updates and use Object.assign to update the objects directly, utilizing the byId map to locate the object to update.
const byId = {};
array.forEach((obj) => byId[obj.id] = obj);
array_two.forEach((obj) => {
  if (!Object.hasOwnProperty(byId, obj.id)) {
    // Create a new object if the ID does not exist.
    byId[obj.id] = obj;
    array.push(obj);
  } else {
    // Update the existing object.
    Object.assign(byId[obj.id], obj);
  }
});

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

Incorporating exotic elements into d3.js, currently visible

I am attempting to insert checkboxes and text within a node. Refer to the image below for my desired outcome. https://i.sstatic.net/YhrvZ.png While I can see the checkbox in the elements view, it is not visible on the page itself. https://i.sstatic.net/ ...

Improving the performance of a function that generates all possible combinations of elements within an array

After coming across this function online, I decided to optimize it. For instance, if we have an input of [1, 2, 3], the corresponding output would be [[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] Below is the code snippet: const combinations = arr = ...

Error code ERR_UNESCAPED_CHARACTERS is being returned for a basic inquiry made on a particular URL

Issue Summary When accessing the URL https://www.eponuda.com/graficke-kartice-cene/gigabyte-radeon-rx-6900-xt-16gb-gddr6-2‎56-bit-gv-r69xtgaming-oc-16gd-graficka-kartica-cena-579068, an error is returned, while other URLs such as https://www.eponuda.com ...

How to manage dropdowns effectively with Selenium WebDriver in Java

Looking for help with selecting options from a drop-down menu. Here is the source code snippet: <div class="multi ng-isolate-scope" isteven-multi-select="" input-model="genders" output-model="filter.genders" button-label="name" item-label="name" tick ...

Implementing a recurring interval for a timer

Currently, I am attempting to create a stopwatch using the following code: var min = 0, sec = 0, censec = 0 $("#startBtn").on("click", function() {// upon clicking start button $(this).hide();// hide start button $("#stopBtn").show();// show stop butto ...

Maintaining jQuery Chosen multiple selection menu open while selecting multiple options

I'm using Chosen to enhance the appearance and functionality of my <select> element with a search input feature. The issue arises when using a <select multiple>; each time the user opens the dropdown menu to select options, it closes afte ...

Unable to start store from localStorage during App initialization

Having trouble setting up my Vuex store with the logged-in user's account details from localStorage. I've looked at numerous Auth examples in Nuxt, but none explain how to retrieve an authToken from localStorage on the client side for subsequent ...

Generating interactive elements in VUE is key

I am unsure about how to dynamically create components without using the <component :is=''> tag. I would like to insert a component into the DOM through JavaScript. Similar to how you would add a new modal in jQuery with $("body").append(" ...

Troubleshooting problems with a JavaScript game that involves guessing numbers

I have been given a challenging Javascript assignment that involves using loops to create a counting betting game. The concept is simple: the User inputs a number, and the computer randomly selects a number between 1 and 10. The User can then bet up to 10 ...

Is the Vue "Unchecking" feature not properly deleting data from the array?

I need to update my function to handle the removal of a networkAudience when its corresponding checkbox is unchecked. Currently, the networkAudience is being added to the array when checked, but not removed when unchecked. What changes should I make to en ...

jQuery Modal activated only once upon clicking

Recently, I've been experiencing a frustrating issue that's giving me a splitting headache. Despite scouring this forum for answers, my problem persists. Here's the situation: I have a button that triggers modals. Upon first click after refr ...

The AJAX request sends the <div> element instead of the <button> element

I'm puzzled as to why this ajax call is passing the div id instead of the button id that I intended. <?php while($info = mysqli_fetch_array($sql)) { echo "<tr> <th>" .$info[& ...

I'm encountering an issue during the code compilation process. Can someone please point out where I am making a mistake and provide guidance on how to resolve it?

I encountered an error in the terminal while attempting to compile the code, but I am having trouble understanding the reason for it. Code: const express = require("express"); const app = express(); console.dir(app); Error: https://i.sstatic ...

Is it possible for me to nest a Firebase collection within another collection?

When gathering user information and favorite foods in a form, I'd like the favorite food data to be nested under the 'users' collection as Likes: const sendPosts = (e) => { e.preventDefault() db.collection("users").add({ ...

React Object is throwing an error - not a function

I need assistance resolving this issue. The error Object(...) is not a function keeps appearing in my code. Here is the snippet of code that seems to be causing the problem: It centers around the declaration of const useStyles = makeStyles(() => ({. ...

Ways to restrict the display or height of a select HTML element

Is there a way to minimize the display or height of a select tag? Here is an image of the desired outcome: I am open to using Javascript, jQuery, CSS, or simply converting it to a list format. I just need guidance on how to achieve this or a sample to re ...

Developing an array-based multiple choice quiz

Being a complete novice, I am currently immersed in designing a multiple-choice quiz using arrays. The questions all follow a similar template: "Which word in the following has a similar meaning to '_________'." To implement this, I have created ...

Placing numerous meshes that are mostly alike but not exactly the same in a scene

We utilize a single geometry that is attached to every mesh within our scene. var geometry = new three.PlaneGeometry(1, 1, 1, 1), Each object has a texture that is generated and cached to form a new material and a mesh for the object. this.material = ne ...

What is the best way to incorporate distinct keys into the React/Material UI Autocomplete feature?

I am currently working on developing a Material UI Autocomplete component that will showcase search results to the user. Some of the option names may be duplicates, but each will have a unique ID associated with it. I am encountering a warning message th ...

Create geometric shapes on Google Maps version 2

Can anyone guide me on how to draw a polygon on Google Maps with user-input coordinates? I have two input fields for latitude and longitude, and when the user clicks the button, I want the polygon to be drawn. The code I currently have doesn't seem to ...