微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何检查一组 javascript 对象的属性是否包含在一组对象中?

如何解决如何检查一组 javascript 对象的属性是否包含在一组对象中?

我有两个数组:

const issues  = [{ id: 'foo',state: { label: 'bar'} }]
const states  = [{ label: 'bar' },{ label: 'baz' }]

如何为包含 state 数组中的 states 的对象过滤问题数组?

我有以下但不起作用

return issues.filter(issue => {
        return states.includes(issue.state)
 })

解决方法

如果状态中的所有值都是 JSON 可字符串化的,例如字符串、布尔值、数字、null 和仅包含 JSON 可字符串化值的数组/对象,那么一种快速的方法与一组 JSON 一起存在:

const issues = [{ id: 'foo',state: { label: 'bar'} }]
const states = [{ label: 'bar' },{ label: 'baz' }]

const stateSet = new Set(states.map(state => JSON.stringify(state)))

const filtered = issues.filter(issue => stateSet.has(JSON.stringify(issue.state)))

如果您不能字符串化为 JSON,则从 this answer 复制 deepCompare 函数,并将其与 some 一起使用:

const issues = [{ id: 'foo',{ label: 'baz' }]

function deepCompare() {
    // ...
}

const filtered = issues.filter(issue => states.some(state => deepCompare(state,issue.state)))
,

具有相同键的两个对象在内存中仍然是不同的对象,因此在它们之间使用相等或标识比较运算符根本行不通。一种相当稳健的方法是检查每个对象之间的所有键/值对是否相同。我创建了一个函数来执行此操作。

const issues  = [{ id: 'foo',state: { label: 'bar'} }]
const states  = [{ label: 'bar' },{ label: 'baz' }]

function objectsMatch(obj1,obj2) {
  const entries1 = Object.entries(obj1);
  const entries2 = Object.entries(obj2);
  if (entries1.length !== entries2.length) {
    return false;
  }
  return entries1.every(([key,value]) => {
    return obj2[key] === value;
  });
}

const matching = issues.filter(issue => {
  return states.some(state => objectsMatch(state,issue.state));
});

console.log(matching);

请注意,您也可以使用 JSON.stringify,但这是有问题的,因为像函数这样的复杂对象不能用 JSON 表示,并且您可能会得到一些误报!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。