给定一个JSON对象,如何根据Key查找项目?

时间:2011-04-15 05:39:09

标签: javascript jquery jquery-plugins

给定一个JSON对象,如:

var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}
]};

我该怎么做:

datagood = data.where(value == 55)

JS / jQuery是否可以这样?感谢

4 个答案:

答案 0 :(得分:13)

jQuery's grep function允许您过滤数组:

var datagood = $.grep(data.items, function (item) {
    return item.value == 55;
});

如果您想要更强大的实用程序,请查看this SO question on JS LINQ libraries

或者,underscore.js对数组/对象操作也很有用。

答案 1 :(得分:4)

答案 2 :(得分:3)

您可以使用Lo-DashUnderscore库_.where()和_.find()函数:

var res1 = _.where(data.items,{value:"55"});
var res2 = _.find(data.items,{value:"55"});

这两个函数之间的区别是_.where()返回所有匹配的记录,而_.find() - 只返回第一个记录。

var data = {items: [
    {value: "21", name: "Mick Jagger"},
    {value: "43", name: "Johnny Storm"},
    {value: "46", name: "Richard Hatch"},
    {value: "54", name: "Kelly Slater"},
    {value: "55", name: "Rudy Hamilton"},
    {value: "79", name: "Michael Jordan"},
    {value: "55", name: "Another Rudy Hamilton"}
]};

var res1 = _.where(data.items,{value:"55"});
var res2 = _.find(data.items,{value:"55"});

document.write('-.where(): ',JSON.stringify(res1),'<br>');
document.write('-.find(): ',JSON.stringify(res2),'<br>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>

答案 3 :(得分:2)

var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}
]};

// using underscore.js http://documentcloud.github.com/underscore/
var t = _(data.items).find(function(x) {
  return x.value == 55;
});

JSON.stringify(t) ; //# => {"value":"55","name":"Rudy Hamilton"}

// using pure javascript
var find = function(items, f) {
  for (var i=0; i < items.length; i++) {
    var item = items[i];
    if (f(item)) return item;
  };
}

t = find(data.items, function(x) {return x.value == "55";});

JSON.stringify(t) ; //# => {"value":"55","name":"Rudy Hamilton"}