You can't use ===
(or ==
) to compare two different arrays. It will check to see if they're the same array, not equivalent arrays.
It's very odd that models
has some entries that are arrays, others that are objects, and others that are simple strings.
It's also odd that you're being asked to find ["350"]
. Does that mean you should find cars that matcy all of the models in that array? Or any of them? Doesn't really matter when the array has only one entry, but arrays by their nature can have multiple entries...
And it's odd that there's an entry in cars
that doesn't have a name
.
Assuming it should be "any," then you need to allow for the fact that some entries in models
are arrays and others aren't.
var myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ ["320"], "X3", "X5" ] },
{ "models":[{ "test": "abcd", key:[{bcc:'hello'}] } , "Panda"] }
]
};
const modelsToFind = ["320"];
const result = myObj.cars.find(car =>
car.models.find(model => {
// If it's not an array, make it one
if (!Array.isArray(model)) {
model = [model];
}
// Does it have any of the models we want?
return model.some(m => modelsToFind.includes(m));
})
);
console.log(result);
That doesn't handle entries in models
that are non-array objects. It's unclear what property in the object one is supposed to look at.
The problem seems quite odd overall.