如何过滤数组中的对象?

尼朱斯

我想用单个对象检查数组内的条件。

let arr = [
  {
    name: "john",
    description: {
      height: 5.5,
      weight: 54,
    },
  },
  {
    name: "mary",
    description: {
      height: 5.8,
      weight: 65,
    },
  },
  {
    name: "smith",
    description: {
      height: 6.1,
      weight: 85,
    },
  },
];

let obj = {
  height: 5.8,
  weight: 65,
};

我想比较数组中的obj,如果它匹配一个,我想获取名称。例如,obj等于结婚。我想印玛丽。这就是我尝试过的。

let result = arr.filter((item) => item.description === obj )
console.log(result.name);
妮娜·斯科茨(Nina Scholz)

您可以使用对象的条目构建过滤器,并迭代所有条目并检查值。然后映射名称。

let array = [{ name: "john", description: { height: 5.5, weight: 54 } }, { name: "mary", description: { height: 5.8, weight: 65 } }, { name: "smith", description: { height: 6.1, weight: 85 } }],
    object = { height: 5.8, weight: 65 },
    filters = Object.entries(object),
    result = array
        .filter(({ description }) => filters.every(([key, value]) => description[key] === value))
        .map(({ name }) => name);

console.log(result);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章