$ .each () does not work when only one item is iterated over?

I had a call to each method for some results getJSON:

    if(data && data.query && data.query.results)
    {                
        $.each(data.query.results.span, function(i, item)
        {
            console.log("Content:" + item.content); // FAILS --> UNDEFINED!!
         });
    }

I could not understand why it did not display anything, although I could see that JSON returned a single result.

So, I deleted each and did the following:

    if(data && data.query && data.query.results)
    {
            console.log("Content:" + data.query.results.span.content); // WORKS!!
    }

Now it works.

Is there no way to use each()when there is only one result?

+3
source share
3 answers

$.each expects an array in the first argument, something like this:

$.each([ data.query.results.span ], function(i, item) { ... } 

must work. Square brackets create one array of elements.

+8
source

$.each() , (- ) .

:

var a = {first: "abc", second: "def"};
$.each(a, function(i, item){...});

, $.each, . "", item "abc". "", "def".

+1

First collapse the collection twice if it is already an array of objects. If not, rewrite the variable nested as an array of objects:

if (MyCollection[0]==undefined) MyCollection = [MyCollection];
$.each(MyCollection, function (key,item) { ....
0
source

Source: https://habr.com/ru/post/1782179/


All Articles