javascript - 根据条件选择 JSON 对象

标签 javascript json

我正在过滤一个大型 json 数据集,我想知道如何垂直选择 json 对象。

举个小例子,我想选择所有作者姓名包含“Evelyn”的书籍

data= [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price":8
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 8
      },
      { "category": "fiction",
        "author": "Evelyn Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }

结果我应该得到:

  { "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "price": 8
          },
          { "category": "fiction",
            "author": "Evelyn Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
          },

我可以这样做吗:

$.each(data,function(i,el)
{
    var newdata;
     if (data.author.contains('Evelyn')) newdata.push()
});

另一种方式:

 data.where( "( n, i ) => n.author.contains('Evelyn') " ) ;

您知道这两种方式的问题出在哪里吗?因为我有一个巨大的数据集,解决这个问题的最快方法是什么?

最佳答案

您可以使用Array.filter:

var filtered = data.filter(function(a){return +(a.price) >= 8;}

或者在author字段上过滤:

var filtered = data.filter(function(a){return /evelyn/i.test(a.author);});
// now [filtered] contains the objects from [data] 
// where 'author' contains 'Evelyn'
// filtered.length => 2
// filtered[0].category => 'fiction'

MDN filter documentation (包括适用于旧版浏览器的填充程序)

关于javascript - 根据条件选择 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20370318/

相关文章:

java - JSONObject 的 names() 方法返回不一致的结果

javascript - 使用可能存在或可能不存在的接口(interface)修改全局

javascript - 当检测到外部点击时关闭菜单

json - jq 变换外部和内部数组

android - 如何在 Android 上的 Retrofit 中处理可以是 ARRAY 或 OBJECT 的参数?

javascript - 如何在mongodb中使用自动生成的id查找数组元素

Javascript正则表达式查找两个冒号之间的任何数字(大于0)

javascript - 获取对象中最后一个最深级别的项目

javascript - Chrome 扩展程序 : How to open a specified link in a new tab by clicking a button in the html popup?

json - WHERE BETWEEN 子句中的 PostgreSQL jsonb 值