Jonathan Foster Jonathan Foster - 6 months ago 19
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.


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.