How do I access the children of a JSON object?

Viewed 5703

Alright, so, I have this one JSON file

{
"status": "success",
"message": {
    "affenpinscher": [],
    "african": [],
    "airedale": [],
    "corgi": [
        "cardigan"
    ],
    "akita": [],
    "appenzeller": [],
    "basenji": [],
    "beagle": [],
    "bluetick": [],
    "borzoi": [],
    "bouvier": [],
    "boxer": [],
    "brabancon": [],
    "briard": [],
    "bulldog": [
        "boston",
        "french"
    ]
  }
}

I need to loop through the list and check if the array of the breed is empty or not.

I've worked with JSON files in the past, but these sort of lists are usually inside some form of Arraylist, which allows me to simply loop through it, but I'm not really sure what I am supposed to do in this scenario.

Is there a way to select all the "children" of message.

This is what I have so far.

$.getJSON("https://dog.ceo/api/breeds/list/all", function (resp) {
    var doglist = $('#doglist');
    $.each(resp.message, function(dog) {
        var dog1 = resp.message;
        doglist.append('<li>' + dog + '</li>')
        var subdog = Object.keys(dog1).length;
        console.log(subdog);        
    });
});

I'm probably not being clear enough.

In my code snippet, there is a

var subdog = Object.keys(dog1).length; 

this returns 15, as expected.

what I need is to do something like

var subdog = Object.keys(dog1.bulldog).length;

and have it return 2

but it needs to be done automatically for all breeds.

Basically loop through the list

8 Answers

try this

$.each(resp.message, function(index, dogs) {
    var subdog = dogs.length;
    console.log(subdog);        
});

You can use Object.values() to get an array of the values of the object and .map() to return .length of each array that is a value of a property within the object

let o = {"status":"success","message":{"affenpinscher":[],"african":[],"airedale":[],"corgi":["cardigan"],"akita":[],"appenzeller":[],"basenji":[],"beagle":[],"bluetick":[],"borzoi":[],"bouvier":[],"boxer":[],"brabancon":[],"briard":[],"bulldog":["boston","french"]}};

let len = Object.values(o.message).map(({length}) => length);

console.log(len);

Do like this:

var subdog = Object.keys(dog1).map(dog => dog1[dog].length);

Then subdog will contain an array of lengths for each breed.

You can access the value by looping through the object and using the key for(let key of myObject) then access it via square brackets like you would an array.

let dogs = {
  "status": "success",
  "message": {
    "affenpinscher": [],
    "african": [],
    "airedale": [],
    "corgi": [
      "cardigan"
    ],
    "akita": [],
    "appenzeller": [],
    "basenji": [],
    "beagle": [],
    "bluetick": [],
    "borzoi": [],
    "bouvier": [],
    "boxer": [],
    "brabancon": [],
    "briard": [],
    "bulldog": [
      "boston",
      "french"
    ]
  }
}

for (let key in dogs.message) {
  if (Array.isArray(dogs.message[key]) && dogs.message[key].length > 0) {
    // Do something here
    dogs.message[key].forEach(d => console.log(d))
  }
}

for( var arr in dogs){
    if(arr.length == 0){
        //code goes here
     }
 }

Hope this works

I re read the question if you want each breed separately and not the total just change it to

  for(var i=0; i<dog1.length;i++){
    subDog[i] = dog1[i].length;
  });

I think that you need to program recursive. And there is no jquery required

Here is a example object and your object

let testObj = {
    lala0: {
        lala1: {
            a: "1"
        },
        foo1: {
            b: "2"
        },
        doo1: {
            c: "3"
        }
    },
    foo0: {
        d: "4"
    },
    doo0: {
        lala1: {
            lala2: {
                e: "5"
            },
            foo2: {
                f: "6"
            },
            doo2: {
                g: "7"
            }
        },
        foo1: {
            lala2: {
                h: "8"
            },
            foo2: {
                i: "9"
            },
            doo2: {
                j: "10"
            }
        },
        doo1: {
            lala2: {
                k: "11"
            },
            foo2: {
                l: "12",
                m: "13"
            },
            doo2: {
                n: "14"
            }
        }
    }
},
dogs = {
"status": "success",
"message": {
    "affenpinscher": [],
    "african": [],
    "airedale": [],
    "corgi": [
        "cardigan"
    ],
    "akita": [],
    "appenzeller": [],
    "basenji": [],
    "beagle": [],
    "bluetick": [],
    "borzoi": [],
    "bouvier": [],
    "boxer": [],
    "brabancon": [],
    "briard": [],
    "bulldog": [
        "boston",
        "french"
    ]
  }
}

function isObject(target) {
    return typeof(target) == "object";
}

function Recursive(obj, i = "") {
    for (let key in obj)
        if (obj.hasOwnProperty(key))
            if (isObject(obj)) {
                value = obj[key];
                if (value == "[object Object]")
                    value = "object";
                console.log(i + key + ": " + value);
                Recursive(obj[key], i + "----|");
            }
}


Recursive(testObj);
console.log("NEW OBJECT!")
Recursive(dogs);

Rewrite the dogs variable with:

let dogs = readJsonFromUrl('http://your.site.com/v1/jsons/...');
Related