Javascript jquery - 从数组对象中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39007387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:07:12  来源:igfitidea点击:

jquery - get value from array object

javascriptjqueryarraysobjectkeyvaluepair

提问by codenoob

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

但我想要做的是遍历对象数组,并将 id 与用户输入的 id 进行比较并返回匹配的值。所以索引应该是无关紧要的

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.

如何解决这个问题。

回答by Nenad Vracar

Instead of result.idyou should use currentElementInLoop.id

而不是result.id你应该使用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);
});

回答by Sean Wang

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

回答by jacqbus

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