我有数组
const arr = [
{id: 1, country: 'Austria'},
{id: 2, country: 'Germany'},
{id: 3, country: 'Austria'},
];
我尝试了以下代码来过滤它。
arry.map((item,idx) => (
item.country== "Austria"?(
console.log(item.id)
)
:
null
))
输出是
1 3
, 但我想在整个过滤器之后获得输出,例如
1,3
我只想要国家为奥地利的 ID,如下所示。
1,3
使用
reduce
功能
const arry = [
{id: 1, country: 'Austria'},
{id: 2, country: 'Germany'},
{id: 3, country: 'Austria'},
];
const result = arry.reduce((acc,item,idx) => {
if(item.country == "Austria"){
if(idx === 0) acc += item.id
else acc += `,${item.id}`
}
return acc
}, '')
console.log(result)
这就是我的过滤方式
const arry = [
{id: 1, country: 'Austria'},
{id: 2, country: 'Germany'},
{id: 3, country: 'Austria'},
];
const result = arry.filter((item, index) => {
if(item.country == "Austria"){
return true
}
else{
return false
}
})
console.log(result)
一行答案:
arr.filter(i => i.country == 'Austria')
onChange={(e)=>{setSearch(e.target.value)}}
users.filter(item=>item.name.toLocaleLowerCase().includes(search.toLocaleLowerCase())).map((item)=>