繁体   English   中英

Javascript - 循环通过嵌套的 object

[英]Javascript - Loop through nested object

我有 1 个阵列,其中包含多个 object 和一个 object。 我如何找到并返回与 object 匹配的数据。 这是我的代码的插图。

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"}]}

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

您不能将Array.includes用于此目的,因为您无法比较两个对象的相等性(只有当它们引用同一个对象时,您才会得到 true)。 相反,您可以使用Array.someArray.every查看是否有任何features object 的所有键/值对在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);

暂无
暂无

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

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