Home > Mobile >  I want to compare two json objects excluding one of the keys from it
I want to compare two json objects excluding one of the keys from it

Time:03-03

I have two objects x,y and i want to compare both of these excluding one of the keys "c"

let x = {a: 5, b: 6, c: "string"}
let y = {a: 5, b: 8, c: "string"}

How i am trying to compare it is -

JSON.stringify(x) === JSON.stringify(y)

Above works but it will compare all keys I want to exclude c in comparison here. What's the best way to achieve this ?

CodePudding user response:

The following code obtains all the keys from object x, removes c from the list, and then performs the comparison.

let x = { a: 5, b: 6, c: "string" };
let y = { a: 5, b: 6, c: "another string" };

console.log(
  Object.keys(x)
    .filter((key) => key !== "c")
    .every((key) => x[key] === y[key])
);

CodePudding user response:

array.sort requires a comparator function. You can use the exact same thing here

function myObjComparator (x, y) {
  if (x.a != y.a) return y.a - x.a;
  return y.b - x.b;
}

CodePudding user response:

let x = {a: 5, b: 6, c: "string"};
let y = {a: 5, b: 8, c: "string"};

delete x.c;
delete y.c;

console.log(JSON.stringify(x) === JSON.stringify(y));

CodePudding user response:

If you don't want to compare deep here is a solution

const x = {a: 5, b: 6, c: "string1"}
const y = {a: 5, b: 8, c: "string2"}

const compare = (obj1, obj2, except = []) => {
    for (const obj1Key in obj1) {
        if (except.includes(obj1Key)) continue;
        if (!obj2.hasOwnProperty(obj1Key)) return false;
        if (obj1[obj1Key] !== obj2[obj1Key]) return false;
    }

    for (const obj2Key in obj2) {
        if (except.includes(obj2Key)) continue;
        if (!obj1.hasOwnProperty(obj2Key)) return false;
    }
    
    return true;
}

console.log(compare(x, y, ['c']));

CodePudding user response:

What about this?

JSON.stringify(x, ['a','b']) === JSON.stringify(y, ['a','b']);

better solution:

function replacer(key, value) {
  // Filtering out properties
  if (key === 'c') {
    return undefined;
  }
  return value;
}
JSON.stringify(x, replacer) === JSON.stringify(y, replacer);

correct better solution:

const filterKeys = (obj) => Object.keys(y).filter(k => k !== 'c').sort()
JSON.stringify(x, filterKeys(x)) === JSON.stringify(y, filterKeys(y));
  • Related