Ihor Herasymchuk
Ihor Herasymchuk

Reputation: 118

How to get JSON property based on another property

Suppose I have a following JSON file:

[
  {
    "id" : "1",
    "name" : "Super shirt",
    "snippet": "Item description here",
    "price" : "some price here",
    "category" : "shirt",
    "pic" : "picture1"

  },
  {
    "id" : "2",
    "name" : "Super duper",
    "snippet": "Item description here",
    "price" : "some price here",
    "category" : "shirt",
    "pic" : "picture2"
  }
]

and so on. How to get a value of "pic" property based on "id" property of each object?. So how to get a picture of each object if I have an id of that object.

Upvotes: 1

Views: 2199

Answers (4)

georg
georg

Reputation: 215009

You're looking for Array.find

picture = data.find(x => x.id == SOME_ID).pic

For older browsers, there's a polyfill on the linked page.

Upvotes: 1

JavidRathod
JavidRathod

Reputation: 483

var data= [{"id" : "1","name" : "Super shirt","snippet": "Item description here","price" : "some price here","category" : "shirt","pic" : "picture1"},
    {"id" : "2","name" : "Super duper","snippet": "Item description here","price" : "some price here","category" : "shirt","pic" : "picture2"}
];
var selected_pic = null;
$.each(data,function(key,value){
    if(value.id == "1"){selected_pic = value.pic;}
});
console.log(selected_pic);

Try Above Code:

Upvotes: 0

aitnasser
aitnasser

Reputation: 1256

Assuming your data structure looks like this:

var arr= [
  {
    "id" : "1",
    "name" : "Super shirt",
    "snippet": "Item description here",
    "price" : "some price here",
    "category" : "shirt",
    "pic" : "picture1"


},
  {
    "id" : "2",
    "name" : "Super duper",
    "snippet": "Item description here",
    "price" : "some price here",
    "category" : "shirt",
    "pic" : "picture2"
  }
];

Then, you can find the pic in your object by searching through the array like this:

function findPicById(data, idToLookFor) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].id == idToLookFor) {
            return(data[i].pic);
        }
    }
}

for example:

var item = findPicByIdId(data, 1);  //return picture1

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68413

use forEach to iterate the array

var obj = [
  {
    "id" : "1",
    "name" : "Super shirt",
    "snippet": "Item description here",
    "price" : "some price here",
    "category" : "shirt",
    "pic" : "picture1"


},
  {
    "id" : "2",
    "name" : "Super duper",
    "snippet": "Item description here",
    "price" : "some price here",
    "category" : "shirt",
    "pic" : "picture2"
  }
];

var pic = "";
obj.forEach( function(value){

   if (value.id == "1" )
   {
      pic = value.pic;
   }

} );
alert(pic);

Upvotes: 0

Related Questions