Skip to content
Advertisement

Javascript – Loop through nested object

I have 1 array with multiple object and an object. How do i find and return the data matching that 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?

Advertisement

Answer

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). Instead you could use Array.some and Array.every to see if any features object has all its key/value pairs duplicated in 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);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement