最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Getting the length of a nested JSON array in JavaScript - Stack Overflow

programmeradmin1浏览0评论
            {
            "wordsacross": [
                {"ACHE": [
                    { "letter":"A" , "square":"A1" }, 
                    { "letter":"C" , "square":"A2" }, 
                    { "letter":"H" , "square":"A3" },
                    { "letter":"E" , "square":"A4" }
                ]},
                {"OPT": [
                    { "letter":"O" , "square":"A6" }, 
                    { "letter":"P" , "square":"A7" }, 
                    { "letter":"T" , "square":"A8" }
                ]}
            ],
            "wordsdown": [
                {"ALPHA": [
                    { "letter":"A" , "square":"A1" }, 
                    { "letter":"L" , "square":"B1" }, 
                    { "letter":"P" , "square":"C1" },
                    { "letter":"H" , "square":"D1" },
                    { "letter":"A" , "square":"E1" }
                ]},
                {"BRO": [
                    { "letter":"B" , "square":"G1" }, 
                    { "letter":"R" , "square":"H1" }, 
                    { "letter":"O" , "square":"I1" }
                ]}
            ]
            }

            $.ajax({
                type: "POST",
                url: "query.words.php",
                data: { puzzleid: vPuzzleId },
                async: false
            }).done(function( msg ) {
                vWords = JSON.parse( msg );
                console.log(vWords);
                console.log("There are "+vWords["wordsacross"].length+" words across");
                for(var i=0;i<vWords["wordsacross"].length;i++)
                {
                    console.log( vWords["wordsacross"][i].length );
                    console.log( vWords["wordsacross"][i][0]["square"] );
                }
            });

I am trying to print out the content of all square items to the console. Both of my attempts at console.log are ing out undefined. How am I to access each square and print it to the console?

Thanks in advance...

            {
            "wordsacross": [
                {"ACHE": [
                    { "letter":"A" , "square":"A1" }, 
                    { "letter":"C" , "square":"A2" }, 
                    { "letter":"H" , "square":"A3" },
                    { "letter":"E" , "square":"A4" }
                ]},
                {"OPT": [
                    { "letter":"O" , "square":"A6" }, 
                    { "letter":"P" , "square":"A7" }, 
                    { "letter":"T" , "square":"A8" }
                ]}
            ],
            "wordsdown": [
                {"ALPHA": [
                    { "letter":"A" , "square":"A1" }, 
                    { "letter":"L" , "square":"B1" }, 
                    { "letter":"P" , "square":"C1" },
                    { "letter":"H" , "square":"D1" },
                    { "letter":"A" , "square":"E1" }
                ]},
                {"BRO": [
                    { "letter":"B" , "square":"G1" }, 
                    { "letter":"R" , "square":"H1" }, 
                    { "letter":"O" , "square":"I1" }
                ]}
            ]
            }

            $.ajax({
                type: "POST",
                url: "query.words.php",
                data: { puzzleid: vPuzzleId },
                async: false
            }).done(function( msg ) {
                vWords = JSON.parse( msg );
                console.log(vWords);
                console.log("There are "+vWords["wordsacross"].length+" words across");
                for(var i=0;i<vWords["wordsacross"].length;i++)
                {
                    console.log( vWords["wordsacross"][i].length );
                    console.log( vWords["wordsacross"][i][0]["square"] );
                }
            });

I am trying to print out the content of all square items to the console. Both of my attempts at console.log are ing out undefined. How am I to access each square and print it to the console?

Thanks in advance...

Share Improve this question asked Aug 19, 2013 at 4:22 EaeEae 4,32116 gold badges58 silver badges93 bronze badges 1
  • what will happen if you add the code console.log(msg) before the line vWords = JSON.parse( msg );? – zzlalani Commented Aug 19, 2013 at 4:27
Add a ment  | 

4 Answers 4

Reset to default 5

vWords['wordsacross'] or vWords.wordsacross (equivalent) contains one array with two elements. When you write vWords['wordsacross'][i] you're accessing a single one of those items. You're then trying to access length or [0] of that single item, but the item is not an array, it is an object.

For i = 0 it is an object that has a property named ACHE and that is an array.

You may thus write:

vWords.wordsacross[0].ACHE.length

The way your object is structured, the property containing the array of letters is a different one for each item in the array, which may be a bit inconvenient. You could get enumerate the object's own properties with Object.keys(vWords.wordsacross[i]), but I'd remend changing your object, if that's an option.

For instance, one item in the wordsacross array could have a word property for which the value would be ACHE and a letters property for which the value would be your array of letters. In that way, you could access vWords.wordsacross[i].letters without having to know that the word happens to be "ACHE":

"wordsacross": [
    {"word": "ACHE",
     "letters": [
        { "letter":"A" , "square":"A1" }, 
        { "letter":"C" , "square":"A2" }, 
        { "letter":"H" , "square":"A3" },
        { "letter":"E" , "square":"A4" }
    ]}
],

Since the letters "A", "C", "H", "E" can be inferred from the word "ACHE" you may be able to get away with just writing:

"wordsacross": [
    { "word": "ACHE";
      "squares": ["A1", "A2", "A3", "A4"]
    }
]

The string "ACHE" can be treated as an array of characters; you can get it's length and you can access the carachter at any given position, wordsacross[0].word[i].

http://jsfiddle/xp8Ww/

for(var i=0;i<vWords["wordsacross"].length;i++)
            {
                var keys =Object.keys(vWords["wordsacross"][i]);
                console.log(keys.length);
                for(var j=0;j<keys.length;j++){
                    var keys2=vWords["wordsacross"][i][keys[j]].length;
                    for(var k=0;k<keys2;k++){
                      console.log(vWords["wordsacross"][i][keys[j]][k]["square"]);
                    }
                }

            }

try vWords.wordsacross only (no brackets) :)

Try this

for (key in vWords) { //Iterate for wordsacross and wordsdown
    console.log(key);
    var words = vWords[key]; //Get the value for wordsacross and wordsdown
    for (var i = 0; i < words.length; i++) { //Iterate over the words
        for (word in words[i]) { //Iterate over the word object
            console.log(word);
            var wordSquares = words[i][word]; //Get the letter and square info for word object
            for (var j = 0; j < wordSquares.length; j++) { //Iterate over the letters
                console.log(wordSquares[j].letter);
                console.log(wordSquares[j].square);
            }
        }
    }
}

This will iterate over all the words in the results and print the letter and squares accordingly

发布评论

评论列表(0)

  1. 暂无评论