Reputation: 143
I have a JSON array like this:
json = [{id:"01.0635.6100",image:"https://www.innotec.nu/InnotecProduktBilder/clearBond.png?ver=0.1",name:"ClearBond",price:"189.00",quantity:"1"},{id:"07.1435",image:"https://www.innotec.nu/InnotecProduktBilder/easygasket.png?ver=0.1",name:"Easy Gasket",price:"200.00",quantity:"2"}]
I am having trouble reading the data directly without going through a loop like each, map etc. I know it should be possible to access a spesific variable inside the array using something like this:
var pid = '07.1435'
json.id[pid].price
json[pid].price
json[id][pid].price
I have tried "every" possible solution but all I end up getting is "Uncaught TypeError: Cannot read property '07.1435' of undefined"
I am sorry if this is a duplicate question, but there it is. If you are able to point me in the right direction I would be very very grateful
Upvotes: 0
Views: 49
Reputation: 363
What you have here is an array of objects. One way to get the objects is to loop over the array like so:
$.each(json, function(index){
console.log(this.id)
console.log(this.image)
});
You can also use $map() or a simple for loop to do that.
Upvotes: 1
Reputation: 12880
You can use the Array#find
method to find the object with the correct ID :
const json = [{id:"01.0635.6100",image:"https://www.innotec.nu/InnotecProduktBilder/clearBond.png?ver=0.1",name:"ClearBond",price:"189.00",quantity:"1"},{id:"07.1435",image:"https://www.innotec.nu/InnotecProduktBilder/easygasket.png?ver=0.1",name:"Easy Gasket",price:"200.00",quantity:"2"}];
console.log(json.find(e => e.id == '07.1435'));
Upvotes: 1