简体   繁体   English

如何在 object 中获取不在 JavaScript 中的另一个 object 中的密钥

[英]How to get keys in an object that is not in another object in JavaScript

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需要得到 ['l', 'b'] 或者可能不在数组中

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);

Here's a recursive function that deep compares the keys of both objects.这是一个递归 function ,它深度比较了两个对象的键。 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所以本质上,它会遍历obj1中的每个嵌套键,并确保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:示例 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM