简体   繁体   English

如何访问JSON对象的子代?

[英]How do I access the children of a JSON object?

Alright, so, I have this one JSON file 好吧,所以,我有这个JSON文件

{
"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. 我以前使用过JSON文件,但是这些列表通常都在某种形式的Arraylist中,它允许我简单地遍历它,但我不确定在这种情况下我应该做什么。

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. 正如预期的那样,这将返回15。

what I need is to do something like 我需要的是做一些事情

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

and have it return 2 并让它返回2

but it needs to be done automatically for all breeds. 但它需要自动完成所有品种。

Basically loop through the list 基本上循环遍历列表

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 您可以使用Object.values()来获取对象值的数组,并使用.map()返回每个数组的.length ,它是对象中属性的值

 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); 

You can use the square bracket syntax to get the value. 您可以使用方括号语法来获取值。

Object.keys(dog1).forEach((dog) => {
    console.log(key) // Will log `bulldog` etc.
    console.log(dog[key].length); // Will log 2, etc. 
});

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation for more info 有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation

Do like this: 这样做:

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

Then subdog will contain an array of lengths for each breed. 然后,subdog将包含每个品种的长度数组。

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. 您可以通过循环遍历对象并使用键for(let key of myObject)来访问该值,然后通过方括号访问它,就像使用数组一样。

 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 并且不需要jquery

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: 用以下内容重写dog变量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM