问题
I'm creating an API that takes a JSON like this:
"hightlights":[
{
"title":"Fun",
"url":"fun/index.html",
"queries":
[
"music",
"artists",
"events",
"internet"
]
},
{
"title":"Internet",
"url":"internet/index.html",
"queries":
[
"javascript",
"web",
"internet",
]
}
]
I need to filter the JSON with a word given by user and return with another JSON with only object that contains the word in "queries".
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",
]
}
My problem is how to nest this values? If anyone can give me some example...I'll appreciate...
回答1:
Try the below:
function getResult(filterBy, objList) {
return objList.hightlights.filter(function(obj) {
return obj.queries.some(function(item){
return item.indexOf(filterBy) >= 0;
});
});
}
Input#1:
getResult("internet", yourObject);
Output #1:
[{"title":"Fun","url":"fun/index.html","queries":["music","artists","events","internet"]},{"title":"Internet","url":"internet/index.html","queries":["javascript","web","internet"]}]
Input #2:
getResult("music", yourObject);
Output #2:
[{"title":"Fun","url":"fun/index.html","queries":["music","artists","events","internet"]}]
回答2:
var xyz = {
"hightlights":[
{
"title":"Fun",
"url":"fun/index.html",
"queries":[
"music",
"artists",
"events",
"internet"
]
},
{
"title":"Internet",
"url":"internet/index.html",
"queries":[
"javascript",
"web",
"internet",
]
}
]
}
no lets say "var word" contains the keywords to be searched, then you could simply do this:
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 should have your required object. Sorry this is very basic. But hope it helps.
回答3:
var search = function(data, query) {
return data.hightlights.filter(function(highlight) {
return highlight.queries.indexOf(query) > -1;
});
}
search(data, "music");
If you have a curry
function available (as from Ramda, Lo-Dash, etc.) you can wrap this:
var search = curry(function(data, query) { ... });
And then you can create simpler functions by passing in the data first:
highlights = search(data);
//...
highlights("music"); //=> those containing "music"
highlights("internet"); //=> those containing "internet"
Update
I know there is already a working solution. But this might be a bit simpler.
This would search inside the queries for subwords:
var search = function(data, query) {
return data.hightlights.filter(function(highlight) {
return highlight.queries.filter(function(q) {
return q.indexOf(query) > -1;
}).length > 0;
});
}
来源:https://stackoverflow.com/questions/27546804/filtering-nested-json-javascript