我正在尝试通过搜索表单过滤一些 API 数据,但不确定如何获得所需的结果,也不知道哪里出错了。
我正在调用一个 API,它返回一个如下所示的对象数组:-
const apiData = [
{
"firstName": "chris",
"lastName": "kundill",
"postcode": "sa11 3fj"
},
{
"firstName": "sam",
"lastName": "white",
"postcode": null
},
{
"firstName": "john",
"lastName": "davies",
"postcode": "sa11 3fj"
},
{
"firstName": "jane",
"lastName": "davies",
"postcode": "sa11 3fj"
},
{
"firstName": "maria",
"lastName": "davies",
"postcode": "sa11 3fj"
},
{
"firstName": "nutter",
"lastName": "dave",
"postcode": "sa11 3fj"
},
{
"firstName": "donna",
"lastName": "duggie",
"postcode": "sa11 3fj"
}
]
我已将搜索表单数据存储在一个对象中,如下所示,NB。并非所有 3 个输入字段都必须填写 :-
const formData = {
"firstName": "Chris",
"postcode": "SA11 3FJ"
}
然后,我获取
formData
对象并将值转换为小写,并通过执行以下操作删除所有空字符串:-
const sanitise = Object.values(formData).map((item) => {
return item.toLowerCase()
}).filter((item) => {
if (item !== '') {
return item
}
})
给我:-
const sanitise = ['chris', 'sa11 3fj']
如何过滤 API 数据以返回包含
sanitise
数组数据的正确对象?
我一直在使用
array.filter
方法,但我找不到正确的条件组合来仅返回正确的对象,而不返回包含 "postcode": "sa11 3fj"
的每个对象
如果您在清理表单数据后将其保留为对象,您可以根据数据集中的每个对象检查其键/值对,而无需在搜索功能中对键进行硬编码。
const data=[{firstName:"chris",lastName:"kundill",postcode:"sa11 3fj"},{firstName:"sam",lastName:"white",postcode:null},{firstName:"john",lastName:"davies",postcode:"sa11 3fj"},{firstName:"jane",lastName:"davies",postcode:"sa11 3fj"},{firstName:"maria",lastName:"davies",postcode:"sa11 3fj"},{firstName:"nutter",lastName:"dave",postcode:"sa11 3fj"},{firstName:"donna",lastName:"duggie",postcode:"sa11 3fj"}];
// `reduce` over the formData entries.
// If the current prop value exists coerce it
// to lowercase (and add the property to the accumulator)
function sanitiseFormData(formData) {
const formEntries = Object.entries(formData);
return formEntries.reduce((acc, [ key, value ]) => {
if (value) acc[key] = value.toLowerCase();
return acc;
}, {});
}
// `search` accepts the data, and the sanitised query
// `filter` over the data and for each object iterate over
// the queryEntries and if every one of the key/value pairs in
// the query matches the key/value pairs in the current object
// return the object
function search(data, query) {
const queryEntries = Object.entries(query);
return data.filter(obj => {
return queryEntries.every(([ key, value ]) => {
return obj[key] === value;
});
});
}
const formData1 = {
firstName: 'Chris',
lastName: '',
postcode: 'SA11 3FJ'
};
const formData2 = {
firstName: 'Donna',
lastName: null,
postcode: 'SA11 3FJ'
};
console.log(search(data, sanitiseFormData(formData1)));
console.log(search(data, sanitiseFormData(formData2)));
附加文档
好吧,如果您只想要特定情况的解决方案,这对我有用:
let filtered = apiData.filter((obj) => obj["firstName"] == sanitise[0] && obj["postcode"] == sanitise[1]); // Just combine the 2 conditions
console.log(filtered);
不确定我是否应该使用
let
或 var
或 const
来表示 filtered
变量,哈哈