gpt4 book ai didi

Javascript如何过滤匹配关键字的数组

转载 作者:行者123 更新时间:2023-11-30 00:26:31 24 4
gpt4 key购买 nike

我有一个深度嵌套的数组,如下所示:

{[{
id: "1",
experts: [
{instruments: [{guitar: ["John", "Maria"],
piano: ["Hans", "Sarah", "Nancy"] }],
name: "Columbia Records", published: "1930"
},
{instruments: [{guitar: ["Pablo"],
drums: ["Jeb", "Xiao"]} ],
name: "Atlas Records", published: "1978"
}
]
]},
{
id: "2",
experts: [
{instruments: [{sitar: ["Anaka", "Reha"],
chello: ["Hans", "Raphael", "Stuart"]} ],
name: "Touchstone Records", published: "1991"
},
{instruments: [{viola: ["Richard", "Farah"],
buss: ["Tina", "Max"]} ],
name: "Atlas Records", published: "1978"
}
]

}

我需要执行分级搜索。例如,如果我的搜索关键字是“Jo”,结果应该是:

[{
id: "1",
experts: [{"instruments": [
"guitar": ["John"]
]
],
"name": "Columbia Records", "published": "1930"
}]

换句话说,每个嵌套级别,我只是根据键进行过滤,如果它不存在,则删除嵌套对象并继续。如果搜索键是“1”,它将返回整个第一个对象。

我正在研究 loadsh 及其采用谓词的过滤函数,但不确定如何实现搜索任意嵌套。

最佳答案

这里看起来很有趣。首先,您的对象声明有很多错误。您缺少结束标记,并且您没有使用 ["key":"value"] 之类的键创建数组,这是针对对象 {"key":"value"}

var testArray = [{
id: "1",
experts: [
{"instruments": {"guitar": ["John", "Maria"],
"piano": ["Hans", "Sarah", "Nancy"] },
"name": "Columbia Records", "published": "1930"
},
{"instruments": {"guitar": ["Pablo"],
"drums": ["Jeb", "Xiao"] },
"name": "Atlas Records", "published": "1978"
}
]
},
{
id: "2",
experts: [
{"instruments": {"sitar": ["Anaka", "Reha"],
"chello": ["Hans", "Raphael", "Stuart"] },
"name": "Touchstone Records", "published": "1991"
},
{"instruments": {"viola": ["Richard", "Farah"],
"buss": ["Tina", "Max"] },
"name": "Atlas Records", "published": "1978"
}
]
}];

一种方法是使用递归,例如:

function deepSearchForValue(obj, searchstring) {
var doesValueExist = function(item) {
if (typeof item === "string") {
return item.toLowerCase().indexOf(searchstring.toLowerCase()) >= 0;
} else {
return doesValueExistRecursive(item);
}
}

var doesValueExistRecursive = function(item) {
for (i in item) {
if (doesValueExist(item[i])) {
return true;
}
}
return false;
}

return obj.filter(doesValueExistRecursive);
}

你可以这样调用它

var matchedItems = deepSearchForValue(testArray, "reh");

console.log("found:");
console.log(matchedItems);

关于Javascript如何过滤匹配关键字的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31215369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com