[英]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.some
和Array.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.