Search a deeply nested value in array of objects in javascript -
i'm trying implement search given value should in array of object key values(there can nested objects). here example. below function take object , query search in array objects key values. so, if match found should filter array.
function searchobj (obj, query) { (var key in obj) { var value = obj[key]; if (typeof value === 'object') { searchobj(value, query); } if (typeof value === 'string' && value.tolowercase().indexof(query.tolowercase()) > -1) { return obj; } } } here dummy data
var demodata=[ {id:1,desc:{original:'trans1'},date:'2017-07-16'}, {id:2,desc:{original:'trans2'},date:'2017-07-12'}, {id:3,desc:{original:'trans3'},date:'2017-07-11'}, {id:4,desc:{original:'trans4'},date:'2017-07-15'} ]; here array i'm filtering object of match
var searchfilter = demodata.filter(function(obj){ return searchobj(obj, 'trans1'); }); console.log(searchfilter); for example: if call searchobj(obj,'2017-07-15') returns particular object if search trans1 or trans should object , return match. i'm kinda stuck appreciated. thanks.
case 1 working because not hitting recursion. in case 2, keep searching after found result.
return object once find.
if (typeof value === 'object') { return searchobj(value, query); } if (typeof value === 'string' && value.tolowercase().indexof(query.tolowercase()) > -1) { return obj; } function searchobj (obj, query) { (var key in obj) { var value = obj[key]; if (typeof value === 'object') { return searchobj(value, query); } if (typeof value === 'string' && value.tolowercase().indexof(query.tolowercase()) > -1) { return obj; } } } var demodata=[ {id:1,desc:{original:'trans1'},date:'2017-07-16'}, {id:2,desc:{original:'trans2'},date:'2017-07-12'}, {id:3,desc:{original:'trans3'},date:'2017-07-11'}, {id:4,desc:{original:'trans4'},date:'2017-07-15'} ]; var searchfilter = demodata.filter(function(obj){ return searchobj(obj, 'trans1'); }); console.log(searchfilter);
Comments
Post a Comment