codenoob codenoob - 3 months ago 10
Javascript Question

jquery - get value from array object

I have an array of object that look like this

var result = [{"id":"1","price":"20.46"},{"id":"2","price":"40.00"}]


right now I can access it by

result[0].price


but what I am trying to do is loop through the array of object, and compare the id to a user inputed id and return the matching value. So the index should be irrelevant

I tried to loop through the array of object, but I probably made some grammar mistake and got nothing back.

var userinputid = 1;

result.forEach(function(){
if(userinputid == result.id){
alert(result.price);
});


How to solve this.

Answer

Instead of result.id you should use currentElementInLoop.id

var result = [{"id":"1","price":"20.46"},{"id":"2","price":"40.00"}]
var userinputid = 1;

result.forEach(function(e) {
  if (userinputid == e.id) alert(e.price);
});