Search code examples
javascriptsearchjavascript-objects

Search through an array of objects and return whole object if a value matches a string or substring


I have multiple objects in an array (I shortened the example, so it doesn't make much sense, but I think it's better to understand the problem):

address_components: [
    {
        id: 1,
        name: "41",
        types: "street_number"
    },
    {
        id: 2,
        name: "Tal",
        types: "route"
    },
    {
        id: 3,
        name: "München",
        types: "city"
    },
    {
        id: 4,
        name: "Deutschland",
        types: "country, political"
    },
]

I want to look through these objects and search for a type, like "country". If a type "country" is found I want the whole object back, so:

{
    id: 4,
    name: "Deutschland"
    types: "country, political"
}

I got the following approach:

var searchFor = "city";
var addressComponent = response.address_components.filter(function(e) {
    return searchFor.indexOf(e.types) != -1;
});

Which works if I search for "city", but not if I search for a substring(?) like "country". Is this approach correct and can I extend it somehow to return the correct result if I sear for "country" in my example?


Solution

  • Assuming that country is the sub-string of types then simply Do it the other way round

    return e.types.indexOf( searchFor ) != -1;