Deepika.P
Deepika.P

Reputation: 29

Check it 2 objects have the same property values

I have 2 objects:

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

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

I want to compare these 2 objects irrespective of isSelected property value and if both objects are the same (except isSelected element value) i want to update itemArr's isSelected as true.

if (JSON.stringify(tempArr) === JSON.stringify(itemArr)) {
  itemArr.isSelected = true;
}

Currently the above code compare both array including isSelected element, how to exclude it while comparing.

Upvotes: 0

Views: 351

Answers (2)

KARASZI István
KARASZI István

Reputation: 31467

If comparing JSON strings are working for you as @Yevgen Gorbunkov pointed out correctly, then you could use destructuring and get rid of the isSelected that way:

const withoutSelected = ({ isSelected, ...other }) => JSON.stringify(other);

if (withoutSelected(tempArr) === withoutSelected(itemArr)) {
  itemArr.isSelected = true;
}

Upvotes: 1

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

Comparing two Object's with JSON.stringify() doesn't seem to be a good idea as the order of keys in both parameters is not guaranteed.

Instead, I would suggest to loop through the Object.keys() with Array.prototype.every() and perform the check:

const tempArr = { bookRetail: 14.99, hierarchyDescription: "GUYS DENIM PANTS [ 0151 ]", isSelected: true,isAvailableInPivot: "Y", style: "VICE NWH NAVY WHITE DC [ M450MBON ]"},
      itemArr = { bookRetail: 14.99, hierarchyDescription: "GUYS DENIM PANTS [ 0151 ]", isSelected: false, isAvailableInPivot: "Y", style: "VICE NWH NAVY WHITE DC [ M450MBON ]"}
      
      itemArr.isSelected = Object
          .keys(tempArr)
          .every(key => 
            key == 'isSelected' || 
            tempArr[key] == itemArr[key])
            
console.log(itemArr)            

Upvotes: 1

Related Questions