Nalla Srinivas
Nalla Srinivas

Reputation: 933

How to get json object from json array using key belongs to one json object

I have a json array like this

[
{ id: 1, name: "larry" },    
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]

now i want to get one json object from this array of json objects ex: i want

{ id: 1, name: "larry" } 

this object from that array of json objects if name=larry . is it possible?

Upvotes: 1

Views: 98

Answers (2)

Nishit Maheta
Nishit Maheta

Reputation: 6031

using jquery $.grep() you can search in json data.

var jsonData = [
  { id: 1, name: "larry" },    
  { id: 2, name: "curly" },
  { id: 3, name: "moe" }
];

var data= $.grep(jsonData, function(element, index){
  return element.name == 'larry';
});

console.log(data[0].id+ "====" + data[0].name);

Upvotes: 1

Edi G.
Edi G.

Reputation: 2422

I'm not sure whether I get your question right, but shouldn't the following work?

var myObj = myJsonResponse[0];

console.log(myObj.id + " " + myObj.name);

Or if you wanna find by name:

var myObj;

for (var i = 0; i < myJsonResponse.length i++){
  // look for the entry with a matching value
  if (obj[i].name == "larry"){
     //found it
     myObj = obj[i];
  }
}

Upvotes: 0

Related Questions