提问人:Aren Trot 提问时间:8/1/2023 更新时间:8/1/2023 访问量:40
在嵌套的对象数组中搜索字符串,并返回匹配的对象作为结果
Search string in nested array of objects and return matched objects as result
问:
我有如下所示的对象数组。它的属性为字符串类型,是一个数组,是嵌套对象input
vertical
platformList
radar_metadata
我想搜索一个字符串并获取那些具有字符串值的对象。它就像我正在尝试实现的搜索功能。
let input = [
{
"vertical": "Partner",
"platformList": [
"Access"
],
"radar_metadata": {
"state": "Verify",
}
},
{
"vertical": "Integration",
"platformList": [
"Identity"
],
"radar_metadata": {
"state": "Closed",
}
}
]
因此,我实现了这个函数来遍历对象元素并获取字符串匹配或包含在对象中的对象。
const filterByValue = (array, string) => {
return array.filter((o) =>
Object.keys(o).some((k) =>
o[k].toString().toLowerCase().includes(string.toLowerCase())
)
);
};
当我得到这个结果1时,我在对象数组中搜索文本,得到的结果如下。Partner
let result1 = filterByValue(input, 'Partner')
----Output----
result1 = [
{
"vertical": "Partner",
"platformList": [
"Access"
],
"radar_metadata": {
"state": "Verify",
}
}
]
现在,当我想搜索文本或文本时,复杂性会增加。因为这些搜索将在嵌套对象 (radar_metadata) 和数组 (platformList) 中执行Ident
Clos
let result2 = filterByValue(input, 'Ident')
let result3 = filterByValue(input, 'Clos')
----Output----
result2 = [
{
"vertical": "Integration",
"platformList": [
"Identity"
],
"radar_metadata": {
"state": "Closed",
}
}
]
result3 = [
{
"vertical": "Integration",
"platformList": [
"Identity"
],
"radar_metadata": {
"state": "Closed",
}
}
]
有人可以告诉我如何修改我的函数以包括这些场景吗?filterByValue
答:
1赞
Starcc
8/1/2023
#1
这是我的解决方案。
const filterByValue = (array, string) => {
return array.filter((o) =>
Object.keys(o).some((k) => {
const value = o[k];
if (typeof value === 'object') {
return filterByValue([value], string).length > 0;
} else if (Array.isArray(value)) {
return filterByValue(value, string).length > 0;
} else {
return value.toString().toLowerCase().includes(string.toLowerCase());
}
})
);
};
1赞
Zarek
8/1/2023
#2
你可以通过分解你的对象来做到这一点:
const filterByValue = (array, string) => {
return array.filter((obj)=>{
// destructure your obj to extract the data
const {vertical, platformList, radar_metadata: {state}} = obj;
// make an array from the destructured data
const data = platformList.concat(state,vertical);
// return if string is included
return data.some( (el)=>el.toLowerCase().includes(string.toLowerCase()) );
});
};
以下是有关解构的更多信息的链接:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
评论