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
}
Misha Karas
  • 89
  • 1
  • 9
  • iterate or return? – Nina Scholz Nov 30 '16 at 08: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. –  Nov 30 '16 at 09:04

3 Answers3

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";
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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;}
kukkuz
  • 41,512
  • 6
  • 59
  • 95
1

That's what JavaScript filters are for.

myObj.quests.filter(item => item.status === 'COMPLETED');
C14L
  • 12,153
  • 4
  • 39
  • 52