Iterazione delle proprietà di un oggetto JavaScript utilizzando jQuery


116

Esiste un modo jQuery per eseguire l'iterazione sui membri di un oggetto, ad esempio in:

    for (var member in obj) {
        ...
    }

Semplicemente non mi piace che questo forsporga dalla mia adorabile notazione jQuery!

Risposte:


210
$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

ogni


Inoltre immagino che l'allarme nnon sia del tutto corretto. Almeno potrebbe esseren.name
Eugene

2
@ Eugene: non capisco il tuo punto. La funzione each accetta un array o un oggetto come primo argomento e una funzione come secondo. Questa funzione viene chiamata per ogni elemento nell'array / ogni proprietà dell'oggetto. Ogni volta che la funzione viene chiamata, ottiene l'indice e il valore / nome e il valore passati come argomenti. Nel mio esempio il parametro "n" sono le due stringhe "John" e "JS". La proprietà "name" sarebbe "undefined".
Tim Büthe

Sì. Mi sbagliavo qui. In qualche modo ho pensato che ogni proprietà in object fosse un altro oggetto con, ad esempio, il nome della proprietà che è una stringa. Ovviamente tutto questo è sbagliato. Mi dispiace tanto. :)
Eugene

4
ognuno ha molte più funzionalità: thisè anche n. return falseinterrompe ogni ciclo ...
andy

56

Puoi usarlo anche eachper gli oggetti e non solo per gli array:

var obj = {
    foo: "bar",
    baz: "quux"
};
jQuery.each(obj, function(name, value) {
    alert(name + ": " + value);
});

9

Questo metodo esaminerà le proprietà degli oggetti e le scriverà nella console con un rientro crescente:

function enumerate(o,s){

    //if s isn't defined, set it to an empty string
    s = typeof s !== 'undefined' ? s : "";

    //iterate across o, passing keys as k and values as v
    $.each(o, function(k,v){

        //if v has nested depth
        if(typeof v == "object"){

            //write the key to the console
            console.log(s+k+": ");

            //recursively call enumerate on the nested properties
            enumerate(v,s+"  ");

        } else {

            //log the key & value
            console.log(s+k+": "+String(v));
        }
    });
}

Passa semplicemente l'oggetto che vuoi iterare:

var response = $.ajax({
    url: myurl,
    dataType: "json"
})
.done(function(a){
   console.log("Returned values:");
   enumerate(a);
})
.fail(function(){ console.log("request failed");});

Usando questo quando un valore è nullo errori con "Errore di tipo non rilevato: Impossibile leggere la proprietà 'length' di null"
JustinStolle

3

In ritardo, ma può essere fatto utilizzando Object.keys come,

var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},
  ulkeys=document.getElementById('object-keys'),str='';
var keys = Object.keys(a);
for(i=0,l=keys.length;i<l;i++){
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';
}
ulkeys.innerHTML=str;
<ul id="object-keys"></ul>

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.