我有这样的js对象
var continents = [
0: {
short: 'na',
countries: [
{
name: 'canada'
},
{
name: 'usa'
},
//...
]
},
1: {
short: 'sa',
countries: [
{
name: 'chile'
},
{
name: 'colombia'
}
]
},
//...
]
我想用一些字符串(例如'col')过滤这个对象以匹配国家名称(contents.countries.name) 过滤函数示例
filter(item => {
return item.name.toLowerCase().indexOf('col'.toLowerCase()) >= 0;
});
期望结果:
1: {
short: 'sa',
countries: [
{
name: 'colombia'
}
]
}
最佳答案
您不仅需要过滤各大洲,还需要过滤其中的国家/地区。
这是一个由两部分组成的过滤器,如下所示。
var continents = [{
short: 'na',
countries: [
{ name: 'canada' },
{ name: 'usa' }
]
}, {
short: 'sa',
countries: [
{ name: 'chile' },
{ name: 'colombia' }
]
}];
function filterByKeyValue(arr, keys, val) {
return arr.filter(item => {
return item[keys[0]].some(subitem => subitem[keys[1]].indexOf(val) > -1);
}).map(item => {
item[keys[0]] = item[keys[0]].filter(subitem => subitem[keys[1]].indexOf(val) > -1);
return item;
});
}
var filtered = filterByKeyValue(continents, [ 'countries', 'name' ], 'col');
console.log(filtered);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<!--
Original filter that method is based on.
var filtered = continents.filter(continent => {
return continent.countries.some(country => country.name.indexOf('col') > -1);
}).map(continent => {
continent.countries = continent.countries.filter(country => country.name.indexOf('col') > -1);
return continent;
});
-->
关于javascript - 对象数组的对象属性中的JS过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47871851/