i have array of object-names
['obj','obj2','objn']
these objects nodes in object
{ obj: { key: value, key2: value, } obj2:{ key3: value } ... }
i know 1 object can do:
for (var key in obj) { if (obj.hasownproperty(key)) { console.log(key) } }
but possible loop through keys of multiple objects without doing duplicates?
assuming parent container object form:
var parentobj = { obj: { key: value, key2: value, } obj2: { key3: value } ... }
also if want include each sub-key once, have
var objnamearray = ['obj','obj2','objn']; var allvalues = []; var usedkeys = {}; for(var = 0; < objnamearray.length; ++i){ // if parent object not have matching sub-object, skip // next iteration of loop if(!parentobj[objnamearray[i]]) { continue; } var currentobj = parentobj[objnamearray[i]]; var subkeys = object.keys(currentobj); for(var j = 0; j < subkeys.length; ++j) { if(usedkeys[subkeys[j]]) { continue; } usedkeys[subkeys[j]] = true; allvalues.push(currentobj[subkeys[j]]); } }
all values keys in each sub-object in array allvalues
, , keys each sub-object available calling object.keys(usedkeys);
. note if sub-objects can have sub-objects, strategy needs adapted support recursion.
Comments
Post a Comment