Javascript - 遍历嵌套对象

时间:2021-02-18 00:08:25

标签: javascript arrays sorting

我有 1 个包含多个对象和一个对象的数组。我如何找到并返回与该对象匹配的数据。这是我的代码的说明。

const cars = [{model:"honda", color:"black", features:[{title:"fast",speed:"100mph"}]}]

const feature = {id:1,title:"fast",speed:"100mph"} 

const match = cars.filter(car => car.features.includes(feature))     

这应该返回

{model:"honda", color:"black", features:[{title:"fast",speed:"100mph"}]}

但它没有,也不知道为什么。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您不能将 Array.includes 用于此目的,因为您无法比较两个对象是否相等(只有当它们引用 相同 对象时,您才会得到 true)。相反,您可以使用 Array.someArray.every 来查看是否有任何 features 对象的所有键/值对都在 feature 中重复:

const cars = [{
  model: "honda",
  color: "black",
  features: [{
    title: "fast",
    speed: "100mph"
  }]
}];
const feature = {
  id: 1,
  title: "fast",
  speed: "100mph"
};

const match = cars.filter(car => car.features.some(f => Object.keys(f).every(k => f[k] == feature[k])));

console.log(match);