gpt4 book ai didi

javascript - 过滤对象数组,其中字段不完整

转载 作者:行者123 更新时间:2023-12-04 08:43:24 24 4
gpt4 key购买 nike

我有以下数组

[
{
"id": 1,
"name": "Ruan Duarte",
"idade": 11,
"work": {
"id": 2,
"name": "React"
}
},
{
"id": 2,
"name": "Raul Dias",
"idade": 13
},
{
"id": 7,
"name": "Caio Ribeiro",
"idade": 60,
"work": {
"id": 4,
"name": "Rails"
}
},
{
"id": 3,
"name": "Felipe Lima",
"idade": 55
},
{
"id": 4,
"name": "Camila",
"idade": 25,
"work": {
"id": 3,
"name": "Phyton"
}
}
]
我有一个这种格式的数组,其中某些 Angular 落的 work.name 字段为空。我尝试按如下方式进行过滤...
array.filter((i) => {
return (
i.work.name.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "")
.includes(search.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""))
)
})
记住我有一个要搜索的输入,并且在状态下它的值是用搜索设置的;
但是我收到一个错误,因为该字段未填写

最佳答案

您可以为 filter 上的对象值添加验证打回来。
在这里,i?.work = i ? i.work : undefined

const array = [
{
"id": 1,
"name": "Ruan Duarte",
"idade": 11,
"work": {
"id": 2,
"name": "React"
}
},
{
"id": 2,
"name": "Raul Dias",
"idade": 13
},
{
"id": 7,
"name": "Caio Ribeiro",
"idade": 60,
"work": {
"id": 4,
"name": "Rails"
}
},
{
"id": 3,
"name": "Felipe Lima",
"idade": 55
},
{
"id": 4,
"name": "Camila",
"idade": 25,
"work": {
"id": 3,
"name": "Phyton"
}
}
]

const search = 'Phy';
console.log(array.filter((i) => {
return (
i?.work?.name?.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "")
.includes(search.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""))
)
}));

关于javascript - 过滤对象数组,其中字段不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64450812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com