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.
现在,从循环的最后一次迭代开始, object
将被设置为其值,并且您将仅返回该对象的价格。
your function replace to
setAll(){
return this.cart.map(({ price }) => +price);
}
i am write jsfiddle example for your question
This worked for me:
setAll(){
var result =this.cart;
var res=Object.keys(result).map(function(key){
return parseInt(result[key].price);
});
return res;
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.