2009-07-01 5 views
6

Il mio obiettivo è quello di ottenere una matrice JSON come questo:json array: come creare nuovi elementi dell'array?

var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}]; 

Come posso ottenere il codice qui sotto per costruire una matrice come sopra uno?

this.dependentProperties = []; //array 
function addDependentProperty(depName, depValue) {  
    dependentProperties.push(new Array(depName, depValue)); 
} 

Utilizzando il metodo push che finiscono per avere una notazione JSON come questo:

args:{[["test1",1],["test2",2]]} 

risposta

28
dependentProperties.push({name: depName, value: depValue}); 
+2

La sintassi si sta guardando dritto in faccia! –

8
var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}]; 

... questo è un array in cui ogni elemento è un associated- array (= hash, = oggetto).

dependentProperties.push(new Array(depName, depValue)); 

... si sta spingendo una (sotto-) matrice nell'array genitore. Non è la stessa cosa di un array associativo. Ora hai una matrice eterogenea.

dependentProperties.push({name: depName, value: depValue}); 

... Questo sta spingendo un array associato nel vostro array di livello superiore. Questo è quello che vuoi. Luca ha ragione.

+0

grazie per la bella spiegazione .... –

0
var myarray = []; 
var myJSON = ""; 

for (var i = 0; i < 10; i++) { 

    var item = { 
     "value": i, 
     "label": i 
    }; 

    myarray.push(item); 
} 

myJSON = JSON.stringify({myarray: myarray}); 
+0

per favore impara come formattare il codice (c'è un punto interrogativo nell'angolo in alto a sinistra della casella di input :-) – kleopatra

1
newObject = { 
"first": "John", 
"last": "Doe", 
"age": 39, 
"sex": "M", 
"salary": 70000, 
"registered": true, 
"interests": [ "Reading", "Mountain Biking", "Hacking" ] 
}