简体   繁体   中英

Return all objects within an array based on if they contain a portion of a string

 [ { "population": 121321313, "location": "American city in the East" }, { "population": 54646546, "location": "Canadian city in the East" }, { "population": 6546467, "location": "American city in the West" }, { "population": 145313, "location": "American city in the South" }, { "population": 12673, "location": "Canadian city2 in the East" }, { "population": 141313, "location": "Canadian city in the South" }, { "population": 1264473, "location": "Canadian city4 in the East" }, { "population": 12673, "location": "Canadian city6 in the South" } ]

I'm trying to figure out how to filter out all the objects within the array based on whether their location is American or Canadian and by Region (East, West, South).

For example, if I want all Canadian cities in the East it would return objects with the index of 1,4,6. How would you filter out the location string within the array based on two parameters, whether they contain American or Candian and East, West, South.

Hopefully the following example will put you on the right track

Assumption: your array is stored in a variable named data

var searchString = "American";
var filteredData = data.filter((item) => {
    return item.location.includes(searchString);
});
for (var i = 0; i < filteredData.length; i++) {
    console.log(filteredData[i].location);
}

Fabio

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM