似乎无法返回我想要的东西。最终,我想返回一个对象数组,或者一个可能与两个不同的部分键/值过滤器匹配的对象。换一种说法: const curQuery = {name:'Nex',tacTechnology:'Dat'}
我计划在表的标题中使用多个过滤器。
const data = [{
"id": "1",
"name": "Unified Communications Portal",
"tacTechnology": "Collaboration"
}, {
"id": "2",
"name": "ACE Training Portal",
"tacTechnology": "Networking Services"
}, {
"id": "3",
"name": "Nexus 5K/2K Training Portal",
"tacTechnology": "Data Center"
}, {
"id": "4",
"name": "XR Training Portal",
"tacTechnology": "Routing"
}]
const curQuery = {name:'Nex'}
function setFilteredItems(curQuery) {
const curQueryKeys = Object.keys(curQuery)
const filteredItems = data.filter(
(item) => {
curQueryKeys.forEach((objKey) => {
if (item[objKey] === undefined || curQuery[objKey] === null){
console.log('its not', item[objKey], curQuery[objKey])
return false;
}
else if(item[objKey].toLowerCase().includes(curQuery[objKey].toLowerCase())) {
console.log('it includes', item[objKey], curQuery[objKey])
return item;
}
})
}
)
console.log('filteredItems', filteredItems )
}
setFilteredItems(curQuery);
期望filterItems为{ “ id”:“ 3”, “名称”:“ Nexus 5K / 2K培训门户”, “ tacTechnology”:“数据中心” },但一无所获。
我在这里创建了一个快速的Codepen:https://codepen.io/bmarker/pen/mddEdma
答案 0 :(得分:1)
问题在于您正在exits the function(类似multipart/form-data
之类的AdminClient
调用中返回。如果您使用常规的forEach
循环,则您的代码将按预期运行,因为continue
用于为for
传递的函数:
return
答案 1 :(得分:0)
您可以从查询对象中获取键/值,并通过使用所需值检查对象的值来迭代条目。
如果您不希望查询的所有属性,可以将Array#every
替换为Array#some
。
function getItems(query) {
var entries = Object.entries(query).map(([k, v]) => [k, v.toLowerCase()]);
return data.filter(o => entries.every(([k, v]) => o[k].toLowerCase().includes(v)));
}
const
data = [{ id: "1", name: "Unified Communications Portal", tacTechnology: "Collaboration" }, { id: "2", name: "ACE Training Portal", tacTechnology: "Networking Services" }, { id: "3", name: "Nexus 5K/2K Training Portal", tacTechnology: "Data Center" }, { id: "4", name: "XR Training Portal", tacTechnology: "Routing" }];
console.log(getItems({ name: 'Nex' }));
.as-console-wrapper { max-height: 100% !important; top: 0; }