Dean Gibson Dean Gibson - 7 months ago 20
Javascript Question

Filter JSON data based on certain properties and values

I have the following JSON object:

{
'name' : 'John',
'friends' : [
{
'id' : 1,
'name' : 'George',
'level' : 10
},
{
'id' : 2,
'name' : 'Stacy',
'level' : 8
},
{
'id' : 3,
'name' : 'Fred',
'level' : 10
},
{
'id' : 4,
'name' : 'Amy',
'level' : 7
},
{
'id' : 5,
'name' : 'Bob',
'level' : 10
}
]
}


So as you can see, you have an object (person?) that has a
name
, and an array of
friend
objects. Each friend object has an
id
,
name
and
level
.

What I'd like to do, is select all the level 10 friends out of that array, and into another variable/object called
var level10Friends
.

I'm using AngularJS and all this needs to happen in my controller, but this doesn't necessarily have to be an AngularJS specific problem, you're welcome to use vanilla JavaScript functions as well.

To be honest I don't even know if this is possible and searching the web doesn't seem to bring anything up about something like this...

Answer

Use Array.prototype.filter(). The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var users = {
  'name': 'John',
  'friends': [{
    'id': 1,
    'name': 'George',
    'level': 10
  }, {
    'id': 2,
    'name': 'Stacy',
    'level': 8
  }, {
    'id': 3,
    'name': 'Fred',
    'level': 10
  }, {
    'id': 4,
    'name': 'Amy',
    'level': 7
  }, {
    'id': 5,
    'name': 'Bob',
    'level': 10
  }]
};
var wantedData = users.friends.filter(function(i) {
  return i.level === 10;
});
console.log(wantedData);