3

I'm trying to iterate over this object containing a array of quests-objects. How would i be able to iterate over each key value pairs to for example return all quests which have the status "completed".

{
    "quests": [
        {
            "title": "A Rum Deal",
            "status": "COMPLETED",
            "difficulty": 2,
            "members": true,
            "questPoints": 2,
            "userEligible": true
        }
    ],
    "loggedIn": false
}
2
  • iterate or return? Commented Nov 30, 2016 at 8:28
  • I don't think you want to "iterate over each key value pairs". You want to iterate over the elements in the array. Key/value pairs are a feature of objects; elements are a feature of arrays. By the way, even if you did not know the word "filter", a Google search for find matching object array javascript property would have turned up an answer right away. Commented Nov 30, 2016 at 9:04

3 Answers 3

2

For iterating you could use Array#forEach

object.quests.forEach(function (a) {
    if (a.status === "COMPLETED") {
        // do something with the data
    }
});

For returning a selection with completed task, you could use Array#filter

var completed = object.quests.filter(function (a) {
    return a.status === "COMPLETED";
});
Sign up to request clarification or add additional context in comments.

Comments

1

Use Array.prototype.filter to filter out the elements which have 'completed' status - see demo below:

var array={"quests":[{"title":"A Rum Deal","status":"COMPLETED","difficulty":2,"members":0,"questPoints":2,"userEligible":0},{"title":"A Rum Deal","status":"NOT_COMPLETED","difficulty":2,"members":0,"questPoints":2,"userEligible":0}],"loggedIn":1};

var result = array.quests.filter(function(e){
   return e.status && e.status === "COMPLETED";
});

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

4 Comments

What is the point of the e.status && part?
check if status is a property of e
It's not necessary. If status is not a property of e, then e.status will be undefined, which will not equate with "COMPLETED".
you are right, it has become a habbit for me to write that check :)
1

That's what JavaScript filters are for.

myObj.quests.filter(item => item.status === 'COMPLETED');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.