gpt4 book ai didi

javascript - 使用javascript中的搜索字符串过滤嵌套的对象数组

转载 作者:行者123 更新时间:2023-11-30 20:53:27 26 4
gpt4 key购买 nike

{  
"rResponse":{
"rDetailsList":[
{
"rDate":"April 01, 2018",
"rList":[
{
"aName":"GOKQG C HQFUDHFPX",
"aNumber":"P3799838628"
},
{
"aName":"IGNDPJR D EKYJYC",
"aNumber":"P3899820579"
}
]
},
{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"",
"aNumber":"A39A4035073"
},
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}
]
}

getFilteredResult(rDetails, searchText) {
const regex = new RegExp(searchText, 'i');
let result= rDetails.filter(a =>
a.rList.some(rItem=>
(rItem.aName.search(regex) > -1) ||
(rItem.aNumber.search(regex) > -1)
))
console.log(result,"filteredResults")
return result;
}

let result=getFilteredResult(rResponse.rDetailsList, "A270M040558"):

我正在使用上述函数根据搜索字符串过滤数据。

我想过滤对象的嵌套数组,保持对象的结构不变上面函数的输出如下,我在这里获取列表的所有对象,而不是只获取一个与搜索文本匹配的对象

{
"rResponse": {
"rDetailsList": [{
"rDate": "Jan 01, 2018",
"rList": [{
"aName": "",
"aNumber": "A39A4035073"
},
{
"aName": "YVTLW K SIGLC",
"aNumber": "A270M040558"
}


]
}]
}

预期的输出是

{
"rResponse": {
"rDetailsList": [{
"rDate": "Jan 01, 2018",
"rList": [
{
"aName": "YVTLW K SIGLC",
"aNumber": "A270M040558"
}


]
}]
}

最佳答案

你有 2 个数组,所以你需要过滤第一个,然后过滤第二个:

const rDetailsList = [  
{
"rDate":"April 01, 2018",
"rList":[
{
"aName":"GOKQG C HQFUDHFPX",
"aNumber":"P3799838628"
},
{
"aName":"IGNDPJR D EKYJYC",
"aNumber":"P3899820579"
}
]
},
{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"",
"aNumber":"A39A4035073"
},
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}
];

const myFilter = (arr, num) => {
const rDetails = arr.filter(det => !!det.rList.find(l => l.aNumber === num));

return rDetails.map(det => {
det.rList = det.rList.filter(l => l.aNumber === num);
return det;
});
};

console.log(myFilter(rDetailsList, 'A270M040558'));

关于javascript - 使用javascript中的搜索字符串过滤嵌套的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917970/

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