javascript - Search object of objects for array value match -
given array parameter ary ["value", "value2"]
i want loop through object of objects find match both array values. i've tried such:
function findmatch (ary) { storagearray = []; mykeys = []; myvalues = []; (var = 0; < ary.length; i++) { (obj in object) { (key in object[obj]) { if (ary[i] in object[obj]) { mykeys.push(key); myvalues.push(object[obj][ary[i]]); } } } storagearray .push(mykeys, myvalues); return storagearray; } var object = { "subobject" : { 'key' : 'value', 'key2' : 'value2', 'key3' : 'value3' }, "subobject2" : { 'key4' : 'value4' }, }
goal: able return k : v
pair each match of value in ary
meaning... since ary
has value
, value2
... want return match object of key : value
, key2 : value2
.
so far a) isn't working , b) doesn't seem efficient way (3 loops...)
it similar way did, , works.
function findmatch(array, object) { var result = []; (var sub in object) { var subobj = object[sub]; (var key in subobj) { (var = 0; < array.length; i++) { if (subobj[key] === array[i]) { result.push({ k: key, v: subobj[key] }); } } } } return result; } var result = findmatch(['value', 'value2'], object); (var = 0; < result.length; i++) { console.log(result[i].k + " : " + result[i].v); }
here way using lookup object:
function findmatch(array, object) { var result = []; var lookup = {}; (var sub in object) { var subobj = object[sub]; (var key in subobj) { var value = subobj[key]; if (!lookup[value]) { lookup[value] = []; } lookup[value].push(key); } } (var = 0; < array.length; i++) { var val = array[i]; var foundarr = lookup[val]; if (foundarr) { (var j = 0; j < foundarr.length; j++) { result.push({ k: foundarr[j], v: val }); } } } return result; } var result = findmatch(['value', 'value2'], object); (var = 0; < result.length; i++) { console.log(result[i].k + " : " + result[i].v); }
Comments
Post a Comment