Employing lodash for object comparison and removal from an array

In my current project, I am using lodash to compare two arrays of objects and extract the differences between them. The goal is to add this difference to the original data set while maintaining the existing data intact. For instance, if there are initially 3 objects in orgData, fetching newData would result in having the same objects from orgData plus an additional object.

var orgData = [{
  "id": 1000,
  "title": "First item"
}, {
  "id": 1001,
  "title": "Second item"
}];

var newData = [{
  "id": 1000,
  "title": "First item"
}, {
  "id": 1001,
  "title": "Second item"
}, {
  "id": 1002,
  "title": "Third item"
}];

The unique identifier for comparison that I am using is the id. However, when attempting to execute my code, I encounter an error stating 'Cannot read property of 'id' undefined', which is understandable given the context.

_.filter(orgData, function(o, x) {
  return o.id !== newData[x].id;
}).forEach(function(x) {
  orgData.push(x);
});

Answer №1

To effectively manage ids, consider using a separate data structure:

var existingIds = [];

_.each(existingData, function(item) {
    existingIds.push(item.id);
})

Check the id of each object in newData and only add it to existingData if its id is not already present in the existingIds array:

_.each(newData, function(item) {
    var id = item.id;
    if (existingIds.indexOf(id) === -1) {
        existingIds.push(id);
        existingData.push(item);
    }
})

If you have any specific criteria for removing objects from an array, please clarify that so we can provide appropriate guidance.

Answer №2

let originalData = [{ "id": 1000, "title": "First item" }, { "id": 1001, "title": "Second item" }];

let updatedData = [{ "id": 1000, "title": "First item" }, { "id": 1001, "title": "Second item" }, { "id": 1002, "title": "Third item" }, { "id": 1003, "title": "Fourth item" }];

let mergedArray = _.union(originalData,updatedData)

console.log(JSON.stringify(mergedArray)) // the combined array will be displayed here

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 best way to retrieve the current page name in DNN and store it in a JavaScript

Having trouble capturing the current DNN page name and assigning it to a variable in javascript. Despite searching online, I haven't been able to find the right code for it. <script type="text/javascript"> var tabName = <% =TabName %>; &l ...

avoiding less than or greater than symbols in JavaScript

I'm encountering an issue while attempting to escape certain code. Essentially, I need to escape "<" and ">" but have them display as "<" and "> in my #output div. At the moment, they show up as "&lt;" and "&gt;" on the page. This ...

XPath Selector in Puppeteer version 22.x

Despite poring over the latest Puppeteer v22.x documentation on XPath, I am still struggling to grasp how to effectively utilize XPath in Puppeteer 22.x. My goal is to click on an element that contains the text 'Next'. Here's the HTML snipp ...

Utilizing Twitter API authentication to prevent hitting rate limits

Currently, I am implementing the Twitter API to showcase the most recent tweets from 4 distinct users on my webpage. It seems that once a certain number of calls are made, an error message appears stating "NetworkError: 400 Bad Request" and prevents the tw ...

Can you reference document.styleSheets[].cssRules[] by specifying a rule name?

I am trying to modify a specific class property value in JavaScript without using an integer as a pointer or looping through all classes to find a matching selectorText value. This is specifically for changing the language displayed on the webpage. <s ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

Retrieve targeted information from the Coin Market Cap API by extracting specific data values using an array

I am looking to retrieve the symbol and other details using the "name" from my array. $.getJSON("//api.coinmarketcap.com/v1/ticker/?limit=0", function(data) { var crypto = [ "Ethereum", "Ripple", "Tron", ]; // used for arr ...

Adding a function to the Window in React & Next.js without using the onload event

Issue with External Script in React Next.js Project I am facing a problem with an external script within my React Next.js project. The script is located at . The script does not work correctly when navigating to the page using the next/link component fro ...

The array was not properly initialized

After scouring this forum in search of someone facing a problem like mine, I am baffled as to why my program is not functioning correctly even though it appears to be solid. I am a beginner in learning Java, so I am unsure if there is a syntax error causin ...

Unable to trigger jQuery onclick event on nested div elements

I'm experiencing an issue with my web-page where two buttons at the top are not responding to a sorting function on the nested #byFilter. Despite trying to apply the onclick(function()) method, it doesn't seem to work. Javascript $(document).re ...

Thymeleaf not triggering JQuery click event

Currently working on a Spring Boot site where I have a list of elements, each containing a link. The goal is to trigger a javascript function when these links are clicked. <div class="col-sm-4" th:each="product : ${productsList}"> <!-- Code... ...

Importing numerical data from a .dat file with numbers organized in columns and storing them into an array in C

#include<stdio.h> #include<stdlib.h> int main() { int array[100]; int index = 0; FILE *filePointer; filePointer = fopen("data.dat","r"); if (filePointer != NULL){ while( !feof(filePointer) ) { fsc ...

EmberJS: Learning how to create a record with a belongsTo relationship

My issue involves using Posts and Comments to explain my problem. In my post_controller, I am trying to create a new record for a comment related to the current post. What is the recommended way to achieve this in Ember? The relationship between Post and ...

Guide to quickly redirecting all 404 links to the homepage on a simple HTML website

Is there a way to automatically redirect clients to the homepage if they click on a broken link in a basic HTML website, instead of displaying a custom 404 page? UPDATE: My website consists of only 5 plain HTML pages hosted on GoDaddy. There is no server- ...

Establish a timeout period for ajax requests using jQuery

$.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something } }); At times, the success function performs well, but sometimes it does not. How can I add a timeout to this ajax re ...

Try fetching new data with React Query by refetching

Whenever a button is clicked, I attempt to fetch new data by calling Refetch. const {refetch,data,isLoading} = useQuery( "getkurs",() =>fetch( `https://free.currconv.com/api/v7/convert? q=${selected.country.currencyId}_IDR&compa ...

Utilizing multiple address parameters within a single-page application

Apologies for the lengthy post. I have encountered an issue with my code after running it through a bot that I can't seem to resolve. In my code, I aim to create functionality where you can visit the address #two, followed by two separate parameters ...

Transitioning a NPM project to the Apache server

Recently, I successfully managed to run a simple example project by following these steps: I downloaded and installed Node.js for windows x64. I then used Git to clone the project from https://github.com/BretCameron/three-js-sample.git Next, I ran t ...

Create an unordered list using the <ul> tag

Creating a ul as input is my goal, similar to this example on jsfiddle: http://jsfiddle.net/hailwood/u8zj5/ (However, I want to avoid using the tagit plugin and implement it myself) I envision allowing users to enter text in the input field and upon hitt ...

The Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...