过滤嵌套的JSON JavaScript [英] Filtering nested JSON javascript

查看:40
本文介绍了过滤嵌套的JSON JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个采用如下JSON的API:

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",
     ]
  }
 ] 

我需要使用用户提供的单词过滤JSON,然后返回另一个JSON,该JSON仅包含包含查询"中单词的对象.

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...

推荐答案

尝试以下操作:

function getResult(filterBy, objList) {
  return objList.hightlights.filter(function(obj) {
   return obj.queries.some(function(item){
     return item.indexOf(filterBy) >= 0;
   });
 });
}


输入#1:


Input#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"]}]

这篇关于过滤嵌套的JSON JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆