javascript - Select object by children array and object values -


i'm getting data object facebook, , select objects in array, has child value of xxx.

the object (simplified of course) structured this:

var friends = [     {         id: 123456,         name: "friend1 name",         education: [             {                 school: {                     name: "school1 name"                 },                 type: "highscool"             }         ]     },     {         id: 3456789,         name: "friend2 name",         education: [             {                 school: {                     name: "school2 name"                 },                 type: "college"             }         ]     } ] 

let's assume want objects education.type = "highscool". how can this, without looping though entire object...?

how can this, without looping though entire object...?

you can't. doesn't have hard:

var highschoolfriends = friends.filter(function(friend) {     var keep = false;     friend.education.some(function(entry) {         if (entry.type === "highschool") {             keep = true;             return true;         }     });     return keep; }); 

that uses es5 array#filter , array#some functions. filter returns new array made of entries in friends array iterator function returns true. some loops through array until iteration function give it returns true (i used instead of array#foreach because can stop early). if need support older browsers don't have yet, they're ones of ones "es5 shim" can give you.

or simple loops:

var i, j; var highschoolfriends = []; var friend;  (i = 0; < friends.length; ++i) {     friend = friends[i];     (j = 0; j < friend.education.length; ++j) {         if (friend.education[j].type === "highschool") {             highschoolfriends.push(friend);             break;         }     } }); 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -