Ways to evaluate the properties of two objects in Angular

On clicking the add new button in my form, I am dynamically adding a new row. The newly entered data is stored in the oldData array as an object.

I need to compare all values in the newData object with the objects in the oldData array. If there already exists an object in the oldData array that matches all the values in the newData object, an error will be logged to the console. Otherwise, the new row will be pushed into the array.

I would appreciate any help in getting my function to work properly.

Answer №1

If the variable oldData contains multiple objects, you can check if newData is included in it using: if(!oldData.includes(newData))

For the original code provided in the description, a simple comparison between single objects can be done like this: if(oldData! = newData)

If the code has been edited as per the description:

addNewType(rowdata) {
    const newData = JSON.stringify(rowdata.value);
    const oldData = JSON.stringify(this.items.value);
    if(oldData.includes(newData)){
        console.log('This element already exists in the detail list');
    }
    else this.addItem(this.createItem(null));           
}

In case oldData has newData occurring at least twice:

addNewType(rowdata) {
    const newData = JSON.stringify(rowdata.value);
    const oldData = JSON.stringify(this.items.value);
    if((oldData.split(newData).length - 1) >= 2){
        console.log('This element already exists in the detail list at least TWICE');
    }
    else this.addItem(this.createItem(null));           
}

Alternatively:

addNewType(rowdata) {
    const newData = JSON.stringify(rowdata.value);
    const oldData = JSON.stringify(this.items.value);
    let newReg= new RegExp(newData, "g");
    if((oldData.match(newReg) || []).length >= 2){
        console.log('This element already exists in the detail list at least TWICE');
    }
    else this.addItem(this.createItem(null));           
}

Answer №2

In my approach, I handle it like so:

private checkAllElementsExist(newData: any[], oldData: any[]): boolean {
    for (const item of newData) {
        var foundItem = oldData.find(x => x.id === item.id);
        if (foundItem === undefined) {
            return false;
        }
    }
    return true;
}

Here is a function that compares the two objects as required in your query.

For reference, you can view an example in StackBlitz utilizing this function

https://stackblitz.com/edit/angular-xscnkf?file=src%2Fapp%2Fapp.component.html

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

Turning off @Output as Observable: A step-by-step guide

I have a query regarding unsubscribing Outputs in Angular. While I am aware that EventEmitter is automatically cleaned up, there was a time when I needed to use an Observable as my Output. Specifically, I wanted to take an Output that emitted events at mos ...

Accessing the state array in React is vital for manipulating and displaying

Is there a way to update the state of my array order conditionally, checking for duplicates, without being able to access order values inside the function addToBasket? It seems like the console.log shows that it's updated and accessible in one instanc ...

Calculating the Bounding Box of SVG Group Elements

Today I encountered a puzzling scenario involving bounding box calculations, and it seems that I have yet to fully understand the situation. To clarify, a bounding box is described as the smallest box in which an untransformed element can fit within. I h ...

Metadata pertaining to the duration of blob videos

I have developed a software that processes camera stream video specifically in Firefox. Using the MediaRecorder API, I create a Blob containing video recordings. To save this blob as a video in local storage, I utilize the FileSaver library: FileSav ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...

An issue has arisen in the production environment on AWS EC2 due to a problem with Nodemailer

When using nodemailer with node.js to send emails, I have set up the following configuration: var transporter = nodemailer.createTransport({ service: 'gmail', host: 'smtp.gmail.com', auth: { ...

Pasting code from a text input field into a function

On my page, there is a textarea labeled "Program" where users can input JavaScript code. When submitted, the page will execute this code and display the result in an output window. One idea I had for implementing this feature was to copy the content of th ...

Create artwork by drawing and adding text to an image before saving it

I am looking to enhance my website by adding a feature that allows users to draw on images hosted on the server. Additionally, I want users to have the ability to add text to the image and save their edits as a new picture. While it may seem like a simple ...

javascript send variable as a style parameter

screen_w = window.innerWidth; screen_h = window.innerHeight; I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles? For example: img { width: screen_w; height: s ...

Node.JS, R, and Python are used for intensive computing tasks such as identifying when a callback function has finished executing and

My Node.js REST API exposes endpoints that trigger R and Python scripts for complex computations. Prior to executing these scripts, I must first identify the callback, assign a unique ID to it, and quickly send back the ID to the consumer. The consumer wil ...

Trouble with fill() function

Check out this JavaScript code snippet I wrote: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill( ...

Locating a class variable using a string chosen from a DropDown menu

In my Tv class, I have several string variables. One requirement is for the user to select an option from a DropDown list and input a value. This entered value should then be stored in the Tv class under a variable with a similar name to the selected optio ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

Using an array to set the center of a map - Google Maps API

I'm attempting to populate a HTML menu with values from a JavaScript multidimensional array using setCenter. Example of HTML Menu <li><a onclick="map.setCenter(cityList[0][1], cityList[0][2]); return false"><script>document.write( ...

Leveraging React Hooks for managing the Data Provider and Data Context functionality

Currently, I am revamping my DataProvider by upgrading it from a class component to a functional component utilizing React Hooks. I suspect that the issue lies in how I am setting up my context consumer, but I am struggling to find an effective way to tes ...

Ensuring validation on an input field following the addition of a new field sharing the same class

Whenever the "Add" button is clicked, an input field with the same class name should be created. However, a validation check needs to be performed before creating the input field. The issue is that the validation is only working the first time and not duri ...

Check if the user input corresponds to the content of an anchor tag by using JavaScript's built-in functionality

Looking to compare a form field input value with anchor tag values using JavaScript. Here is my form field with text input and a button: <form action="#"> <input type="text" id="desc" value=""> <input name="submit" tabindex="1" value= ...

The placeholder text feature for Google custom search is ineffective when using the Edge browser

After adding the following code to the end of the Google custom search script, I encountered an issue: window.onload = function(){ document.getElementById('gsc-i-id1').placeholder = 'Search'; }; Although this code successfully added ...

Error message from Google Adsense: The registration landing URL modifier is null

For the past few days, I've been encountering a persistent error message on all web pages where I have Adsense banners: "Uncaught TypeError: Cannot call method 'registerLandingUrlModifier' of null" I have been using the asynchronous script ...

The art of creating drop shadows in Three.js

Is there a method to create a shadow without needing a "ground" plane to project it on? I prefer this option so that when the camera moves around the object, it doesn't appear as though the shadow is passing through the ground. I am currently utilizi ...