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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.