What is the easiest way to search in JSON by attribute?

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

Is there any method for getting a JSON object with code='en' from the above JSON array in jQuery?

I could do this with a for loop, but I thought there might be an easier way to do this.

+5
source share
3 answers

Use the jquery grep function . You are not really looking for an object, you are looking for an array of objects (names).

Finds array elements that satisfy the filter function. The original array is not affected.

  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> 

Another is the Array # find 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 = input.names.find(item => { return item.code == 'en' }) console.log(result); 
+7
source

Use the Array.prototype.filter function in vanilla JS to filter an object - see demo below:

 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 version is even simpler:

 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); 
+7
source

If you don’t want to do this with a for loop, try using the ES5 array function filter

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

Source: https://habr.com/ru/post/1270573/


All Articles