0

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

1
  • convert to object jQuery.parseJSON(json) and then try. Commented Jun 18, 2018 at 12:23

2 Answers 2

1

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'));

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.