2015-05-08 27 views
11

Ho una matrice di dati. In a ci sono 10 campi e nelle b ci sono 10 campiUnire due array in un oggetto Json

var a = [ "siddharth", "sid", "anything", "something", "nothing", ] 
var b = [ "23", "67", "10", "10", "90" ] 

Sto cercando di creare un JSON da queste matrici come a come chiave e b come valori, come illustrato di seguito:

{ "siddharth" : "23", "sid" : "67" } 

Come posso ottenere questo utilizzando javascript o jquery. Il mio codice attuale è

var convert = '{'+datatest.columnHeaders[i].name +":"+datatest.rows[0][i]+'}'; 
     pair = convert;/*JSON.stringify(convert);*/ 
     array.pairArray.push(pair); 
+0

Duplicazione domanda? Non è JSON.stringify (convert); lavoro? – VikrantMore

risposta

14

Assumendo entrambe le matrici sono sempre la stessa lunghezza:

var obj = {} 
for (var i = 0; i < a.length; i++) { 
    //or check with: if (b.length > i) { assignment } 
    obj[a[i]] = b[i] 
} 
2

var a = [ "siddharth", "sid", "anything", "something", "nothing" ]; 
 
var b = [ "23", "67", "10", "10", "90" ]; 
 

 
var c = {}; 
 
$.each(a, function(i,v) { 
 
    c[ v ] = b[ i ]; 
 
}); 
 

 
$('body').append(JSON.stringify(c)); 
 
//Output: {"siddharth":"23","sid":"67","anything":"10","something":"10","nothing":"90"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

1

È possibile creare l'oggetto pianura e usarlo come contenitore mappatura:

var a = [ "siddharth", "sid", "anything", "something", "nothing" ]; 
var b = [ "23", "67", "10", "10", "90" ]; 
var obj = {}; 
for (i = 0; i < a.length; i++) { 
    obj[a[i]] = b[i]; 
} 
alert(JSON.stringify(obj)); 

prega di fare riferimento al How to create a hash or dictionary object in JavaScript per ulteriori informazioni

1

Si avrebbe bisogno tra virgolette il nome e il valore, altrimenti si finisce con una stringa come {siddharth:23,sid:67}:

// mock the data 
 
var datatest = { 
 
    columnHeaders: [ { name: "siddharth" }, { name: "sid" }, { name: "anything" }, { name: "something" }, { name: "nothing" } ], 
 
    rows: [[ "23", "67", "10", "10", "90" ]] 
 
}; 
 

 
var json = '{'; 
 
for (var i = 0; i < datatest.columnHeaders.length; i++) { 
 
    if (i > 0) json += ','; 
 
    json += '"' + datatest.columnHeaders[i].name + '":"' + datatest.rows[0][i] +'"'; 
 
} 
 
json += '}'; 
 

 
// show result in StackOverflow snippet 
 
document.write(json);

2

Questo esempio è uguale all'esempio di tymeJVs, ma usa forEach loop per array. Per me sembra più corto.

var obj = {}; 
a.forEach(function(item, i) { 
    obj[item] = b[i]; 
}); 
console.log(JSON.stringify(obj)); // {"siddharth":"23","sid":"67","anything":"10","something":"10","nothing":"90"} 
1

Shortest posso ottenere utilizzando la funzione di grassi freccia ES6, carta, ridurre & computed property names

var a = ["siddharth", "sid", "anything", "something", "nothing", ] 
 
var b = ["23", "67", "10", "10", "90"] 
 

 
const mergeArrToJSON = (a, b) => a 
 
    .map((item, i) => ({[item]: b[i]})) 
 
    .reduce((json,val)=>Object.assign({},json,val)) 
 

 
console.log(mergeArrToJSON(a, b))

0

Se siete disposti ad aggiungere un altro famoso di terze parti libreria javascript utilità

Lodash, utilizzare zipObject:

_.zipObject(a, b); 

sottolineatura, utilizzare object:

_.object(a, b); 
0

Se si è liberi di utilizzare plugin aggiuntivi quindi

UNDERSCORE

è quello che state cercando

_.object(['moe', 'larry', 'curly'], [30, 40, 50]); 
=> {moe: 30, larry: 40, curly: 50} 

Codice di riga singolo. Basta includere questo js

https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js