我想做的是使用另一个对象过滤一个对象。我有它适用于名称或电子邮件之类的键,但问题是地址字段需要递归检查值。
我有以下对象:
{
"id" : 1,
"name": "Michael",
"surname": "Smith",
"emailAddress": "m.smith@gmail.com",
},
{
"id": "2",
"name": "Sam",
"surname": "Smith",
"emailAddress": "s.smith@gmail.com",
"address": {
"text": "123 Fake Street, Some Place, United kingdom",
"street_number": "123",
"route": "Fake Street",
"locality": "Some Place",
"country": "UK",
"postcode": "HP18",
"lat": 51.648858999292999,
"lng": 4.08207329992999786,
}
},
{
"id": 3,
"name": "Josh",
"surname": "Fradley",
"emailAddress": "myemai@gmail.com",
"address": {
"text": "1 Apple Park Way, Cupertino, CA, USA",
"street_number": "1",
"route": "Apple Park Way",
"locality": "Cupertino",
"administrative_area_level_1": "California",
"country": "US",
"postcode": "95014",
"lat": 37.3346326,
"lng": -122.01268240000002,
}
}
]
示例搜索对象
{
"name": "",
"phone": "",
"address": "",
"emailAddress": "myemai@gmail.com"
}
我用于电子邮件和姓名字段的代码
let res = array.filter(o =>
Object.keys(searches).every(k =>
o[k] && o[k].length ? removeDiacritics(o[k].toLowerCase()).indexOf(removeDiacritics(searches[k].toLowerCase())) >= 0 : true
));
我正在努力解决的问题是如何搜索作为对象的地址键,例如,如果我搜索“ address”:“ Fake Street”,它应该返回ID 2
有什么建议吗?
编辑:我忘了提到过滤器数组是动态的,因此我无法在“地址”中添加硬代码,在此我将其用作对象的示例
答案 0 :(得分:0)
您可以使用局部函数并检查嵌套对象的对象值。
var data = [{ id: 1, name: "Michael", surname: "Smith", emailAddress: "m.smith@gmail.com" }, { id: "2", name: "Sam", surname: "Smith", emailAddress: "s.smith@gmail.com", address: { text: "123 Fake Street, Some Place, United kingdom", street_number: "123", route: "Fake Street", locality: "Some Place", country: "UK", postcode: "HP18", lat: 51.648858999293, lng: 4.082073299929998 } }, { id: 3, name: "Josh", surname: "Fradley", emailAddress: "myemai@gmail.com", address: { text: "1 Apple Park Way, Cupertino, CA, USA", street_number: "1", route: "Apple Park Way", locality: "Cupertino", administrative_area_level_1: "California", country: "US", postcode: "95014", lat: 37.3346326, lng: -122.01268240000001 } }],
search = { name: "", phone: "", address: 123, emailAddress: "" },
result = data.filter(o => Object.entries(search).every(([k, v]) => {
function check(value) {
return value && typeof value === 'object'
? Object.values(value).some(check)
: value.toString().includes(v);
}
if (v === '') return true;
if (k in o) return check(o[k]);
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }