0

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" } ]
5
  • What is the end result you want here? Do you want to return an array of all of the objects' prices? like [3200, 300, 100, 4500]? Commented Feb 16, 2018 at 13:38
  • It'll be much easier to answer this with a bit more information; nothing apart from your title tells us that you're using Vue, for example. If you provide a bit more information about what you're trying to do, it'll be easier for other to help you achieve that. Commented Feb 16, 2018 at 13:42
  • I want to return only values with prices using vuejs Commented Feb 16, 2018 at 13:53
  • Right now its only returning one price item Commented Feb 16, 2018 at 13:54
  • 1
    You should use prices = cart.map(({price}) => +price); to get all prices from the cart array. Commented Feb 16, 2018 at 14:00

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Right now object will be set to its value from the last iteration through the loop, and you will return the price of that object only.

3 Comments

This should be comment
I thought about that, but it does also contain the information in the answer above it.
Ok, extracted a comment from the answer.
0

your function replace to

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

i am write jsfiddle example for your question

3 Comments

using this function I am getting babel-loader error
@IgorOgnichenko edit your answer adding your jsfiddle instead of commenting. Try to make a readable, simple and complete answer
0

This worked for me:

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

         },  

Comments

Your Answer

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.