按属性搜索JSON的最简单方法是什么?

时间:2017-08-04 08:37:11

标签: javascript jquery arrays json

"names": [
    {
        "id": 17,
        "user_id": 9,
        "code": "de",
        "name": "Ich bin Hans",
        "created_at": "2017-07-31 12:43:19",
        "updated_at": "2017-07-31 12:43:19"
    },
    {
        "id": 18,
        "user_id": 9,
        "code": "en",
        "name": "My name is Hans",
        "created_at": "2017-07-31 12:43:19",
        "updated_at": "2017-07-31 12:43:19"
    }
]

是否有任何方法可以从jQuery中的上述JSON数组中获取带有code='en'的JSON对象?

我可以用for循环来做,但我想也许有一种更简单的方法。

3 个答案:

答案 0 :(得分:7)

使用Jquery grep function。实际上你没有搜索对象,你正在搜索一个对象数组(名称)。

  

查找满足过滤函数的数组元素。原始数组不受影响。



 var input = {names:[{id:17,user_id:9,code:"de",name:"Ich bin Hans",created_at:"2017-07-31 12:43:19",updated_at:"2017-07-31 12:43:19"},{id:18,user_id:9,code:"en",name:"My name is Hans",created_at:"2017-07-31 12:43:19",updated_at:"2017-07-31 12:43:19"}]};
 
var result = $.grep(input.names, function(obj) {
    return obj.code === "en";
});
console.log(result);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

另一个是Array#find功能

&#13;
&#13;
var input = {names:[{id:17,user_id:9,code:"de",name:"Ich bin Hans",created_at:"2017-07-31 12:43:19",updated_at:"2017-07-31 12:43:19"},{id:18,user_id:9,code:"en",name:"My name is Hans",created_at:"2017-07-31 12:43:19",updated_at:"2017-07-31 12:43:19"}]};
 
var result = input.names.find(item => {
   return item.code == 'en'
})
console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:7)

在vanilla JS中使用Array.prototype.filter函数来过滤输出对象 - 请参阅下面的演示:

var obj={names:[{id:17,user_id:9,code:"de",name:"Ich bin Hans",created_at:"2017-07-31 12:43:19",updated_at:"2017-07-31 12:43:19"},{id:18,user_id:9,code:"en",name:"My name is Hans",created_at:"2017-07-31 12:43:19",updated_at:"2017-07-31 12:43:19"}]};

var result = obj.names.filter(function(e){return e.code == 'en'})
console.log(result);

ES6版本更简单:

var obj={names:[{id:17,user_id:9,code:"de",name:"Ich bin Hans",created_at:"2017-07-31 12:43:19",updated_at:"2017-07-31 12:43:19"},{id:18,user_id:9,code:"en",name:"My name is Hans",created_at:"2017-07-31 12:43:19",updated_at:"2017-07-31 12:43:19"}]};

var result = obj.names.filter(e => e.code == 'en');
console.log(result);

答案 2 :(得分:0)

如果您不想使用for循环,请尝试使用ES5数组函数,过滤

names = names.filer(function(item) {
  return item.code === 'en'
})