【发布时间】:2020-05-10 08:03:59
【问题描述】:
我有一个这样的 JSON 对象
xyz = {
"101": {
"categoryName": "ectronics",
"categorslug": "electronics",
"catId": "101",
"name": [
{
"childCategoryName": "Cameras",
"childCategorySlug": "cameras",
"childCategoryId": "102",
"childCategoryParentId": "109"
},
{
"childCategoryName": "Accessories",
"childCategorySlug": "cameras-and-accessories",
"childCategoryId": "102",
"childCategoryParentId": "111"
},
{
"childCategoryName": "ras & Accessories",
"childCategorySlug": "cameras-and-accessories",
"childCategoryId": "102",
"childCategoryParentId": "112"
}
]
},
"109": {
"categoryName": "shion",
"categorslug": "fashion",
"catId": "109",
"name": [
{
"childCategoryName": "Fashion Accessories",
"childCategorySlug": "fashion-accessories",
"childCategoryId": "110",
"childCategoryParentId": "109"
}
]
},
"118": {
"categoryName": "Baby & Kids",
"categorslug": "baby-and-kids",
"catId": "118",
"name": [
{
"childCategoryName": "Baby Footwear",
"childCategorySlug": "baby-footwear",
"childCategoryId": "119",
"childCategoryParentId": "118"
}
]
}
}
现在我有一个基于搜索词的类别过滤器,我必须减少对象,我正在这样做,但问题是我无法从匹配的对象中减少它。
我正在尝试的解决方案是,
topIds = (event) => {
let rs = [];
let inn = '';
let cat = xyz;
for (let i in cat){
for( let j in cat[i].name ){
inn = cat[i].name[j].childCategoryName
if ( inn.toLowerCase().search(event.target.value.toLowerCase()) !== -1 ){
rs.push(cat[i].name[j].childCategoryParentId)
}
}
}
console.log('Filtered Ids', rs);
this.elm(cat, rs)
}
elm = (cat, rs) => {
let filtered = rs.map(function (k){
return cat[k]
})
console.log('Filtered va;ues', filtered);
return filtered;
}
它工作正常,但没有匹配它返回的完整对象,任何建议我在这里做错了什么。
所以,从技术上讲,如果用户说搜索“相机”
它应该像这样返回,
{
"101": {
"categoryName": "ectronics",
"categorslug": "electronics",
"catId": "101",
"name": [
{
"childCategoryName": "Cameras",
"childCategorySlug": "cameras",
"childCategoryId": "102",
"childCategoryParentId": "109"
}
]
}
}
提前谢谢你们。
【问题讨论】:
-
rendredCategory或state在 xyz 中不存在 -
为了避免这种混乱,我将我的问题更新为简单的 JS 语句。
-
“返回完整对象”是指返回
xyz的完整内容,而不仅仅是与键关联的对象值?或者你的意思是它只返回映射到键的对象值,而不是一个新对象,如你的示例所示? -
或者你的意思是,它返回的是键
109而不是101处的对象? -
我发布了一个答案,你没有给出任何反馈?
标签: javascript arrays reactjs filter reduce