首页 > 解决方案 > 如何检查对象是否具有某些属性

问题描述

我有一个带有一些非常特定键的对象。如何检查另一个对象是否具有完全相同的键?例如:

let myOb = {
  name: "somebody",
  class: {
    number: 9,
    section: "C"
  },
  address: {
    house: 22,
    street: "Eg street"
    PIN: 7893
  }
}

if (newOb.containsAll(myOb)) { // this is just a replacement function
  // do stuff
}

我想匹配newObtomyOb并查看它们是否具有确切的键。所以,newOb应该有一个name, class, address; newOb.class应该有一个numberand section; newOb.address应该有house,streetPIN.

我已经知道了hasOwnProperty()。我想知道如果涉及多个键,是否有更简单的方法来做到这一点。

标签: javascriptobjectkey

解决方案


您可以比较两个对象的(递归)键集。

const
  myObjA = {
    name: "somebody",
    class: { number: 9, section: "C" },
    address: { house: 22, street: "Eg street", PIN: 7893 }
  },
  myObjB = {
    name: "somebody else",
    class: { number: 1, section: "A" },
    address: { house: 11, street: "Another st", PIN: 0000 }
  };

// Adapted from: https://stackoverflow.com/a/53620876/1762224
const gatherKeys = obj => {
  const
    isObject = val => typeof val === 'object' && !Array.isArray(val),
    addDelimiter = (a, b) => a ? `${a}.${b}` : b,
    paths = (obj = {}, head = '') => Object.entries(obj)
      .reduce((product, [key, value]) =>
        (fullPath => isObject(value)
          ? product.concat(paths(value, fullPath))
          : product.concat(fullPath))
        (addDelimiter(head, key)), []);
  return new Set(paths(obj));
};

const
  diff = (a, b) => new Set(Array.from(a).filter(item => !b.has(item))),
  equalByKeys = (a, b) => diff(gatherKeys(a), gatherKeys(b)).size === 0;

console.log(equalByKeys(myObjA, myObjB));
.as-console-wrapper { top: 0; max-height: 100% !important; }


推荐阅读