简体   繁体   English

Javascript - 循环通过嵌套的 object

[英]Javascript - Loop through nested object

I have 1 array with multiple object and an object.我有 1 个阵列,其中包含多个 object 和一个 object。 How do i find and return the data matching that object.我如何找到并返回与 object 匹配的数据。 Here is an illustration of my code.这是我的代码的插图。

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))     

This should return这应该返回

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

but it does not and not sure why.但它没有也不知道为什么。 Can someone help?有人可以帮忙吗?

You can't use Array.includes for this purpose as you can't compare two objects for equality (you will only get true if they refer to the same object).您不能将Array.includes用于此目的,因为您无法比较两个对象的相等性(只有当它们引用同一个对象时,您才会得到 true)。 Instead you could use Array.some and Array.every to see if any features object has all its key/value pairs duplicated in feature :相反,您可以使用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