假设我有对象
let x = { "people" :{
"Sally": "value",
"Bob" : "other value"
},
"cars" :{
"Saab" : "this",
"Chevy": "that"
},
"trees":{
"Birch" : "what",
"Oak" : "where"
}
}
我想搜索,所以如果我搜索“S”,我会得到一个数组
{ "people" :{
"Sally": "value",
},
"cars" :{
"Saab" : "this",
}
}
如果我搜索“b”,我会得到:
{ "people" :{
"Bob" : "other value"
},
"trees":{
"Birch" : "what",
}
}
或者“bo”会返回
{ "people" :{
"Bob" : "other value"
}
如果我搜索“e”我会得到
{ "cars" :{
"Chevy": "that"
}
}
请注意,搜索“e”不会捕获“people”和“trees”。
strut 将具有固定深度,我们只想捕获与过滤器匹配且没有子级的 keys(我们对匹配的值也不感兴趣,只是键)。
添加 npm 依赖项是可以接受的。
尝试的解决方案:
filteredList(unfiltered,searchVal) {
return unfiltered.filter(search=> {
return search.toLowerCase().includes(searchVal.toLowerCase())
})
}
显然还有更多内容,但我不确定该往哪个方向前进。
最佳答案
这是一个基本的尝试。它看起来工作得很好,但我非常确定它可能会做得更好。但我不知道怎么办。
let x = {
"people": {
"Sally": "value",
"Bob": "other value"
},
"cars": {
"Saab": "this",
"Chevy": "that"
},
"trees": {
"Birch": "what",
"Oak": "where"
}
}
let search = "B";
let result = {};
for (let key in x) {
let tmp = {};
for (let subKey in x[key]) {
if (subKey.includes(search)) { // Use startsWithif you want even substring that aren't at the beginning
tmp[subKey] = x[key][subKey];
}
if (Object.keys(tmp).length > 0) {
result[key] = Object.assign({}, tmp);
}
}
}
console.log(result)
如果您想要任意深度,您应该尝试使用某种递归,但这会更复杂。
关于Javascript嵌套对象过滤创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49932506/