搜索对象数组,如果值与字符串或子字符串匹配,则返回整个对象

时间:2017-10-18 10:58:59

标签: javascript search javascript-objects

我在一个数组中有多个对象(我缩短了示例,所以它没有多大意义,但我认为理解这个问题会更好):

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"
    },
]

我想查看这些对象并搜索类型,例如" country"。如果是#34;国家"发现我希望整个对象回来,所以:

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

我有以下方法:

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

如果我搜索" city"哪个有效,但是如果我搜索像#34; country"这样的子字符串(?)则不行。 这种方法是否正确,如果我为#34; country"在我的例子中?

2 个答案:

答案 0 :(得分:2)

假设 country 是类型的子字符串,那么只需反之亦然

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

答案 1 :(得分:1)

你颠倒过的东西。  return e.types.indexOf(searchFor)!= -1;

  var 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"
        }
    ]
    
    var searchFor = "political";
    
    var response = address_components.filter(function(e) {
        return e.types.indexOf(searchFor) != -1;
    });
    
    console.log(response);