Himmators
Himmators

Reputation: 15006

Loop through all keys of multiple objects once?

I have an array of object-names

['obj','obj2','objN']

These objects are nodes in an object

{
  obj: {
    key: value,
    key2: value,
  }
  obj2:{
    key3: value
  }
...
}

I know that i for one object I can do:

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(key)
  }
}

but is it possible to loop through all keys of multiple objects without doing any duplicates?

Upvotes: 1

Views: 3812

Answers (2)

Will R.
Will R.

Reputation: 453

Assuming a parent container object with the form:

var parentObj = 
{
    obj: {
        key: value,
        key2: value,
    }
    obj2: {
        key3: value
    }
    ...
}

Also if we want to include each sub-key only once, we have

var objNameArray = ['obj','obj2','objN'];
var allValues = [];
var usedKeys = {};

for(var i = 0; i < objNameArray.length; ++i){
    // If the parent object does not have a matching sub-object, skip to the
    // next iteration of the 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 the values from all the keys in each sub-object will then be in the array allValues, and all the keys from each sub-object will be available by calling Object.keys(usedKeys);. Note that if sub-objects can also have sub-objects, this strategy needs to be adapted to support recursion.

Upvotes: 1

guest271314
guest271314

Reputation: 1

If interpret Question correctly, try utilizing Object.keys()

var data = {
  obj: {
    key: 1,
    key2: 2,
  },
  obj2:{
    key3: 3
  }
};

for (var key in data) {
  console.log(Object.keys(data[key]))
}

Upvotes: 0

Related Questions