javascript - Performing deep search within object without using nested loops (lodash) -
i trying check if value found inside of array contained deep in object without having use multiple & in loops. want know if there elegant way achieve this. first thought use lodash's _.includes, doesn't seem iterate on array in sub-object.
//collection (i'm trying reach person_id in people array) var tables = { 12: { table_info: { name: 'test' }, people: [ //i want check inside of array { person_id: 123 }, { person_id: 233 } ] } //what i'm looping on match id's var people = [ { name: 'john doe', id: 123 }, { name: 'jane doe', id: 245 } ] //loop (var = 0; < people.length; i++) { if (_.includes(tables, people[i].id)) //would love simple solution { console.log("match"); } else { console.log("no match"); } }
why not create own function , use if know data structure?
//collection var tables = { 12: { table_info: { name: 'test' }, people: [ { person_id: 123 }, { person_id: 233 } ] } }; var peopletofind = [ { name: 'john doe', id: 123 }, { name: 'jane doe', id: 245 } ]; function findpeopleintables(people, tables){ let peoplefound = []; (var key in tables) { // make sure doesnt come prototype if (tables.hasownproperty(key)) { tables[key].people.foreach(function (person){ peopletofind.foreach(function(persontofind){ if (person.person_id === persontofind.id){ peoplefound.push(persontofind); } }); }); } } return peoplefound; } let foundpeople = findpeopleintables(peopletofind, tables); foundpeople.foreach(function(person){ console.log('found "' + person.name + '" id ' + person.id); });
also can search in objects using recursive methods :
function findvalueinobject(value , object){ let type = typeof(object); if(type !== 'string' && type !== 'number' && type !== 'boolean'){ (var key in object) { // make sure doesnt come prototype if (object.hasownproperty(key)) { if( findvalueinobject(value , object[key])){ return true; } } } } if(object === value){ return true; } return false; } //collection var tables = { 12: { table_info: { name: 'test' }, people: [ { person_id: 123 }, { person_id: 233 } ] } }; var peopletofind = [ { name: 'john doe', id: 123 }, { name: 'jane doe', id: 245 } ]; peopletofind.foreach(function(person){ if(findvalueinobject(person.id, tables)){ console.log('matched: ' + person.id + ' '+ person.name); } });
Comments
Post a Comment