Tuesday, 15 February 2011

arrays - Filtering a list of Objects with lists- Javascript -



arrays - Filtering a list of Objects with lists- Javascript -

what effective filter list has objects lists in them. have been looking @ underscore's _.filter function takes takes arrays , returns arrays.

i want take object , filter word.

for example, how filter:

[ {level: "title 1", details: [ {real: "there go", fake: "there_we_go"}, {real: "where it", fake: "where_is_it"}, {real: "the dog jumped", fake: "the_dog_jumped"}, ] }, {level: "title 2", details: [ {real: "there is", fake: "there_it_is"}, {real: "car flying", fake: "car_is_flying"}, {real: "driving fun", fake: "driving_is_fun"} ] }, {level: "title 2", details: [ {real: "there is", fake: "there_we_go"}, {real: "where dog", fake: "where_is_the_dog"}, {real: "the dog died", fake: "the_dog_died"}, {real: "i tired", fake: "i_am_tired"}, ]} ];

by word "the"

such returns

[ {level: "title 1", details: [ {real: "there go", fake: "there_we_go"}, {real: "the dog jumped", fake: "the_dog_jumped"}, ] }, {level: "title 2", details: [ {real: "there is", fake: "there_it_is"}, ] }, {level: "title 2", details: [ {real: "there is", fake: "there_we_go"}, {real: "where dog", fake: "where_is_the_dog"}, {real: "the dog died", fake: "the_dog_died"}, ]} ];

notice when filter word "the" want maintain has word "the" part of it, such "there"...and went check if word "the" in "real" index of objects within detail's array.

you can utilize filter, have apply 1 time on each of inner lists , 1 time on outer list:

var phrase = "the".touppercase(); homecoming _.filter(_.map(data, function(item) { homecoming { level: item.level, details: _.filter(item.details, function(detail) { homecoming detail.fake.indexof(phrase) > -1; }) }; }), function(item) { homecoming item.details.length > 0; });

from illustration cannot infer whether need outer filter @ all, or whether not want drop items empty details list.

javascript arrays object underscore.js javascript-objects

No comments:

Post a Comment