简体   繁体   English

javascript vuejs对象数组在循环中仅返回一项

[英]javascript vuejs object array returning only one item in the loop

I am trying to iterate over an array of objects instead its returning only one item here is the code: 我正在尝试遍历对象数组,而不是它仅返回以下一项的代码:

setAll(){
  var result =this.cart;
  for (var key in result) {
    var obj = result[key];
  }
  return obj.price;
}

and the test data 和测试数据

 [ { "id": 5, "price": 3200, "quantity": 8, "name": "juice" }, { "id": 6, 
  "price": 300, "quantity": 6, "name": "rice" }, { "id": 8, "price": "100", 
  "quantity": 1, "name": "water" }, { "id": 7, "price": "4500", "quantity": 
   1, "name": "meat" } ]

You are iterating through the array and only returning the last object. 您正在遍历数组,并且仅返回最后一个对象。 This code: 这段代码:

for (var key in result) {
   var obj = result[key];
}

does nothing other than set obj to the last item in the list. 除了将obj设置为列表中的最后一项外,什么都不做。

现在,从循环的最后一次迭代开始, object将被设置为其值,并且您将仅返回该对象的价格。

your function replace to 您的功能替换为

setAll(){
  return this.cart.map(({ price }) => +price);
}

i am write jsfiddle example for your question 我为您的问题写jsfiddle示例

This worked for me: 这为我工作:

          setAll(){
          var result =this.cart;
          var res=Object.keys(result).map(function(key){
            return parseInt(result[key].price);
          });
          return res;

         },  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM