5

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?

informatik01
16.5k11 gold badges82 silver badges110 bronze badges
asked Aug 17, 2016 at 22:46

4 Answers 4

10

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

answered Aug 17, 2016 at 22:50
Sign up to request clarification or add additional context in comments.

3 Comments

you are right, this solved it. will accept when time runs out
yeah - that's better solution than my.
@codenoob If your id's are unique its better to use find result.find((e) => e.id == userinputid).price; jsfiddle.net/Lg0wyt9u/1139
1

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);
 }
});
answered Aug 17, 2016 at 22:49

Comments

1

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

answered Aug 17, 2016 at 22:51

Comments

0

use the element value parameter or the index parameter

result.forEach(function (elementVal) {
 if (userinputid === elementVal.id){
 alert(elementVal.price);
 }
});
answered Feb 10, 2023 at 11:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.