Home > Mobile >  How to get keys in an object that is not in another object in JavaScript
How to get keys in an object that is not in another object in JavaScript

Time:08-06

const obj1 = {
  a: 5,
  e: {
    c: 10,
    l: {
      b: 50,
    },
  },
};

const obj2 = {
  a: 5,
  e: {
    c: 10,
  },
};

need to get ['l', 'b'] or maybe not in the array

CodePudding user response:

This would work. Without checking the levels and assuming the unique field names.

const obj1 = {
  a: 5,
  e: {
    c: 10,
    l: {
      b: 50,
    },
  },
};

const obj2 = {
  a: 5,
  e: {
    c: 10,
  },
};

const getAllKeys = (obj) => {
  let keyNames = Object.keys(obj);
  Object.values(obj).forEach((value) => {
    if (typeof value === "object") {
      keyNames = keyNames.concat(getAllKeys(value));
    }
  });
  return keyNames;
};

const getFilteredKeys = (keySet1, keySet2) =>
  keySet1.filter((key) => !keySet2.includes(key));
  
const output = getFilteredKeys(getAllKeys(obj1), getAllKeys(obj2));

console.log(output);

CodePudding user response:

Here's a recursive function that deep compares the keys of both objects. This also takes into account the structure and nesting of the children.

So essentially, it goes through each nested key in obj1 and makes sure that there's an equivalent key in the same location in obj2

Your example

const obj1 = {
  a: 5,
  e: {
    c: 10,
    l: {
      b: 50,
    },
  },
};

const obj2 = {
  a: 5,
  e: {
    c: 10,
  },
};


const missingKeys = []
function compare(obj1, obj2) {
  for (let prop in obj1) {
    if (obj2[prop]) {
      if (typeof obj1[prop] === 'object' && typeof obj2[prop] === 'object') {
        compare(obj1[prop], obj2[prop])
       } 
    } else {
      if (typeof obj1[prop] === 'object') {
        compare(obj1[prop], {})
      }
      missingKeys.push(prop)
    }     
  }
}

compare(obj1, obj2)
console.log(missingKeys)

Example 2:

const obj1 = {
  a: 5,
  e: {
    c: 10,
    l: {
      b: 50,
      d: 20,
    },
  },
  z: 50
};

const obj2 = {
  a: 5,
  e: {
    c: 10,
  },
  b: 50, // shares same key name but nested in different location
  l: 50, // also shares same key but nested differently
  z: 50,
};


const missingKeys = []
function compare(obj1, obj2) {
  for (let prop in obj1) {
    if (obj2[prop]) {
      if (typeof obj1[prop] === 'object' && typeof obj2[prop] === 'object') {
        compare(obj1[prop], obj2[prop])
       } 
    } else {
      if (typeof obj1[prop] === 'object') {
        compare(obj1[prop], {})
      }
      missingKeys.push(prop)
    }     
  }
}

compare(obj1, obj2)
console.log(missingKeys)

  • Related