Jonathan Foster Jonathan Foster - 1 year ago 78
Javascript Question

Working with objects within arrays in a for loop javascript

In the following code, I have an array which contains objects which each contain another object. I'd like to do a for loop which targets one of the elements inside the innermost object.

var myArray = [
{nemo : {type: "fish", scales: "yes"}},
{bubbles : {type: "fish", scales: "yes"}},
{jimmy : {type: "turtle", scales: "no"}}
function findType (array, animalType) {
var newArray = [];
for (i = 0; i < array.length; i ++){
if (array[i][*what goes here?*].type == animalType){
return newArray;
findType(myArray, "fish");

The problem I'm having is to get down to the level I want the names of the fish (i.e. nemo, bubbles) would need to be known in each loop of the for loop, and these names are different each time. What would be a way to go down past this level into the object that I want? Thank you.

Answer Source

You can get the list of an object's attributes with Object.keys()

In your case you can do:

    if (array[i][Object.keys(array[i])[0]].type == animalType){

    //you can see it like this for the first fish :
    //array[i] ---> {nemo : {type: "fish", scales: "yes"}}
    //Object.keys(array[i]) ---> ["nemo"]
    //array[i]["nemo"] ---> {type: "fish", scales: "yes"}

But I agree with the others that you may consider changing your data structure.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download