Reputation: 2853
I am trying to write a filter function which takes in an object as a parameter and the query string as its second parameter. The function should return the list of all the values from the object that match the query string.
For example
var data = [{
label: 'Cars',
children: [{
label: 'Volkswagan',
children: [{
label: 'Passat'
}]
}, {
label: 'Toyota'
}]
}, {
label: 'Fruits',
children: [{
label: 'Grapes'
}, {
label: 'Oranges'
}]
}];
function filter(data, query){}
filter(data,'ra'); //['Grapes', 'Oranges']
My question is how to tackle the nested 'children' property for each indexed object?
Upvotes: 0
Views: 53
Reputation: 227200
You want to use recursion for this.
function filter(data, query){
var ret = [];
data.forEach(function(e){
// See if this element matches
if(e.label.indexOf(query) > -1){
ret.push(e.label);
}
// If there are children, then call filter() again
// to see if any children match
if(e.children){
ret = ret.concat(filter(e.children, query));
}
});
return ret;
}
Upvotes: 1
Reputation: 88
Try using recursive calls based on the data type of each property. For example, in the case of a nested property that's an array, you will want to call filter on each element of that array. Similar logic in the case that the nested element is an object, you want to look at each property and call filter. I wrote this off the cuff, so I haven't tested all of the corner cases, but it works for your test example:
var results = [];
filter(data,'ra'); //['Grapes', 'Oranges']
console.log(results);
function filter(data,query){
for(var prop in data){
//array
if(Array.isArray(data[prop])){
for(var i = 0; i < data[prop].length; i++){
filter(data[prop][i],query);
}
} else if (typeof data[prop] === "object"){
filter(data[prop],query);
} else if(typeof data[prop] === "string"){
if(data[prop].indexOf(query) > -1){
results.push(data[prop]);
}
}
}
}
Upvotes: 1