Verify if two items possess identical property values

There are 2 items:

1. obj1 = { bookRetail: 14.99, hierarchyDescription: "GUYS DENIM PANTS [ 0151 ]", isSelected: true, isAvailableInPivot: "Y", style: "VICE NWH NAVY WHITE DC [ M450MBON ]"}

2. obj2 = { bookRetail: 14.99, hierarchyDescription: "GUYS DENIM PANTS [ 0151 ]", isSelected: false, isAvailableInPivot: "Y", style: "VICE NWH NAVY WHITE DC [ M450MBON ]"}

I need to compare these 2 objects without considering the isSelected property, and if they are identical (except for the value of isSelected), I want to set obj2's isSelected to true.

if (JSON.stringify(obj1) === JSON.stringify(obj2)) {
  obj2.isSelected = true;
}

Currently, the code above compares both objects including the isSelected property, how can I exclude it from the comparison.

Answer №1

Using JSON.stringify() to compare two Objects may not be reliable due to the unpredictable order of keys in the parameters.

It is recommended to iterate through the keys of the objects using Object.keys() along with Array.prototype.every() for a more accurate comparison:

const object1 = { name: 'Alice', age: 30 },
      object2 = { name: 'Bob', age: 25 };
      
object2.isEqual = Object
  .keys(object1)
  .every(key => 
    key === 'isEqual' || 
    object1[key] === object2[key]);
    
console.log(object2);

Answer №2

When comparing JSON strings as advised by @Yevgen Gorbunkov, consider using destructuring to eliminate the need for isSelected:

const removeSelected = ({ isSelected, ...rest }) => JSON.stringify(rest);

if (removeSelected(tempData) === removeSelected(itemData)) {
  itemData.isSelected = true;
}

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

Tips for Effectively Adding Deciphered JSON Data into a Mysql Database

I have been struggling to figure out how to get my php code working with my database by searching online, but I'm having trouble understanding it all! That's why I decided to reach out and ask for help or guidance on this issue. Any assistance wo ...

JavaScript Filtering JSON Data Based on Date Range

I am attempting to filter a basic JSON file based on a specified date range, with both a start date and an end date. Below is the function I have created for this task: var startDate = new Date("2013-3-25"); var endDate = new Date("2017-3-2 ...

What could have caused the lack of output from the render function?

I've been working on generating my navigation drawer from JSON data and have everything functioning using components. Now, I'm in the process of refactoring to functions for better performance and to enhance my knowledge of React and JavaScript. ...

Configuring a spinner to display a selected item using JSON

I am currently developing an android application that requires users to choose a country and city using a spinner. To retrieve the necessary data from a JSON file, I use the following code: String state = json.data.getState(); String city = json.data.ge ...

Guide on Declaring an Array in a Node Module and Another JavaScript File (Mongodb)

As a beginner in node.js and programming, I am on a journey to understand how to retrieve a variable's value from Mongodb. Within my app.js file, I have the 'data' variable set up. var data = require("./public/assets/js/data.js"); app.get(& ...

Creating a JSX syntax for a simulated component and ensuring it is fully typed with TypeScript

Looking for some innovative ideas on how to approach this challenge. I have a test helper utils with added types: import { jest } from '@jest/globals' import React from 'react' // https://learn.reactnativeschool.com/courses/781007/lect ...

Submitting an image blob to a database using the FormBuilder

I'm facing an issue with uploading a file blob into the same DB as my form. Here is my form: this.accForm = this.formBuilder.group({ team_leader: ['', Validators.required], hotel_name: ['', Validators.required], address: [&a ...

The use of callbacks is ineffective in addressing the asynchronous nature of

Hello everyone, I'm currently working on a weather app and I'm facing an issue with the asynchronous behavior of useState. I've come across some suggestions on Stack Overflow that using a callback in the useState function might solve the pro ...

Is there a more efficient method to achieve this task using JavaScript or jQuery?

Here is the code snippet I am currently using: $(document).ready(function() { //Document Ready $(".examples .example1").click(function() { $(".examples .example1 div").fadeToggle("slow"); $(".examples .example1").toggleClass('focused') ...

How can I resolve the Vue warning about an unknown custom element <password-input>?

I've been working on resolving an error within a component, but unfortunately, I'm still encountering issues. The error message is as follows: [Vue warn]: Unknown custom element: - have you registered the component correctly? For recursive co ...

What could be causing this error to occur when running my React app and clicking the submit button on the form?

CodeBlock.js import React from "react"; import { useState } from "react"; import axios from 'axios' const CodeBlock=()=>{ const [formData, setFormData]=useState({name:'', password:''}); const hand ...

Using React.js to create table cells with varying background colors

For my React application, I am working with a table that utilizes semantic ui. My goal is to modify the bgcolor based on a condition. In most cases, examples demonstrate something like bgcolor={(condition)?'red':'blue'}. However, I requ ...

The Express API will only provide the initial key-value pair of an object in the response

I'm working on fetching nested data objects. Although I can successfully retrieve the object data in the console, I encounter an issue when attempting to access this data using return res.json(imageObject). Instead of retrieving all key-value pairs of ...

Interacting with server-side data using JQuery's $.ajax method and handling JSON

The JSON response returned from the request is not being recognized. request = $.ajax({ url: "form_handler.php", type: "post", dataType: "json", data: serializedData }); The PHP code within form_handler.php that generates ...

CORS Policy Blocking React and Express Access to Fetch Data from Origin

Currently, I am diving into the world of React and Express in an attempt to enable local file uploads from a React component and have Express handle the incoming files. Unfortunately, no matter what methods I try, I keep encountering this error message: A ...

Manipulating CSS styles with jQuery

Trying to update the UL image in the CSS directory using jQuery for a Twitter stream: as tweets are displayed, want to change the avatar of the account associated with each post. Using .css is straightforward, but struggling to modify the URL for the new i ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...

What is the process for generating an attribute in a system?

If I want to create an element using plain JavaScript, here is how I can do it: var btn = document.createElement('button'); btn.setAttribute('onClick', 'console.log(\'click\')'); document.body.appendChild( ...

Guide on how to have controller wait for promise to be resolved by an Angular service

Currently, I have a service that initiates an AJAX request to the backend. Service: function RetrieveCompanyDataService(options) { this.url = '/company'; this.Companies = undefined; this.CompaniesPromise = ...

What is the meaning of MVVM "binder" and how is it used?

I've been conducting research online to gain a deeper understanding of the MVVM architecture in general. According to Wikipedia, the key components of the MVVM pattern are: Model View View Model Binder This is the first time I have come across the ...