我正在创建一个采用这样的JSON的API:
"hightlights":[
{
"title":"Fun",
"url":"fun/index.html",
"queries":
[
"music",
"artists",
"events",
"internet"
]
},
{
"title":"Internet",
"url":"internet/index.html",
"queries":
[
"javascript",
"web",
"internet",
]
}
]
我需要使用用户给出的单词过滤JSON并使用另一个JSON返回,其中只有包含"查询"中的单词的对象。
If word === 'music', receive:
{
"title":"Fun",
"url":"fun/index.html",
"queries":[
"music",
"artists",
"events",
"internet"
]
}
If word === 'internet', receive:
{
{
"title":"Fun",
"url":"fun/index.html",
"queries":[
"music",
"artists",
"events",
"internet"
]
},
{
"title":"Internet",
"url":"internet/index.html",
"queries":[
"javascript",
"web",
"internet",
]
}
我的问题是如何嵌套这个值?如果有人能给我一些例子......我会感激......
答案 0 :(得分:4)
尝试以下方法:
function getResult(filterBy, objList) {
return objList.hightlights.filter(function(obj) {
return obj.queries.some(function(item){
return item.indexOf(filterBy) >= 0;
});
});
}
输入#1:
getResult("internet", yourObject);
输出#1:
[{"title":"Fun","url":"fun/index.html","queries":["music","artists","events","internet"]},{"title":"Internet","url":"internet/index.html","queries":["javascript","web","internet"]}]
输入#2:
getResult("music", yourObject);
输出#2:
[{"title":"Fun","url":"fun/index.html","queries":["music","artists","events","internet"]}]
答案 1 :(得分:0)
var search = function(data, query) {
return data.hightlights.filter(function(highlight) {
return highlight.queries.indexOf(query) > -1;
});
}
search(data, "music");
如果您有curry
功能可用(来自 Ramda , Lo-Dash 等),您可以将其换行:
var search = curry(function(data, query) { ... });
然后您可以通过先传入数据来创建更简单的函数:
highlights = search(data);
//...
highlights("music"); //=> those containing "music"
highlights("internet"); //=> those containing "internet"
我知道已有一个可行的解决方案。但这可能会有点简单。
这将在查询中搜索子词:
var search = function(data, query) {
return data.hightlights.filter(function(highlight) {
return highlight.queries.filter(function(q) {
return q.indexOf(query) > -1;
}).length > 0;
});
}
答案 2 :(得分:0)
var xyz = {
"hightlights":[
{
"title":"Fun",
"url":"fun/index.html",
"queries":[
"music",
"artists",
"events",
"internet"
]
},
{
"title":"Internet",
"url":"internet/index.html",
"queries":[
"javascript",
"web",
"internet",
]
}
]
}
不要说“var word”包含要搜索的关键字,那么你可以这样做:
var arr = [];
for(var i in xyz['highlights']){
var queries = xyz['highlights']['queries'];
for(j in queries){
if (word == queries[j]){
arr.push(xyz['highlights'][i]);
continue;
}
}
}
arr应该有你需要的对象。对不起,这是非常基本的。但希望它有所帮助。