codenoob
codenoob

Reputation: 539

jQuery - get value from array object

I have an array of object that looks like this:

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

Right now I can access it like this:

result[0].price 

But what I am trying to do is loop through the array of objects and compare the id to a user inputted id and return the matching value. So the index should be irrelevant.

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

var userinputid = 1;

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

How to solve this?

Upvotes: 5

Views: 42607

Answers (4)

user21186692
user21186692

Reputation:

use the element value parameter or the index parameter

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

Upvotes: 0

jacqbus
jacqbus

Reputation: 477

You forgot about index:

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

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

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122135

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

Upvotes: 10

Sean Wang
Sean Wang

Reputation: 780

You are missing a end brace. And you need to have the function use the element value parameter or the index parameter. Try

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

Upvotes: 1

Related Questions