2009-07-13 18 views
11

ho:Merge chiavi array e array di valori in un oggetto in Javascript

var keys = [ "height", "width" ]; 
var values = [ "12px", "24px" ]; 

E mi piacerebbe per convertirlo in questo oggetto:

{ height: "12px", width: "24px" } 

In Python, c'è il semplice linguaggio dict(zip(keys,values)). C'è qualcosa di simile in jQuery o in plain Javascript, o devo farlo a lungo?

risposta

13

semplice funzione JS sarebbe:

function toObject(names, values) { 
    var result = {}; 
    for (var i = 0; i < names.length; i++) 
     result[names[i]] = values[i]; 
    return result; 
} 

Naturalmente si potrebbe anche effettivamente implementare funzioni come zip, ecc come JS supporta i tipi di ordine superiore che rendono questi funzionali-lingua-ismi facile: D

+3

Il lungo che è, quindi :( – itsadok

+0

Se i nomi hanno lo stesso tasto, questa funzione fallirà – user1927627

2
function combineObject(keys, values) 
{ 
    var obj = {}; 
    if (keys.length != values.length) 
     return null; 
    for (var index in keys) 
     obj[keys[index]] = values[index]; 
    return obj; 
}; 


var your_obj = combine(your_keys, your_values); 
+0

eh, ti ho visto è stato risolto in modo rimosso il commento, che poi risposto a - Evviva per la conversazione asincrona: D Si dovrebbe anche evitare il nuovo Oggetto dato che l'Oggetto può essere cambiato, ma {} è spec sa usare l'origina l Costruttore di oggetti. – olliej

+0

La funzione è ancora errata. combineObject (["height", "width"], ["12px", "24px"]). height restituisce erroneamente "24px". –

+0

Grazie, l'ho risolto in base al tuo commento, ma non sono sicuro che possa essere un problema, dal momento che una volta che qualcuno cambia l'oggetto è di proposito, quindi forse è meglio essere impliciti su tutti gli oggetti che avrai. –

0

Nel modulo jQuery-Utils project, il modulo ArrayUtils ha implementato una funzione di chiusura.

//... 
zip: function(object, object2, iterator) { 
    var output = []; 
    var iterator = iterator || dummy; 
     $.each(object, function(idx, i){ 
     if (object2[idx]) { output.push([i, object2[idx]]); } 
    }); 
    return output; 
} 
//... 
+2

Hmm, ma allora cosa si fa con la serie di tuple? – itsadok

1

Si potrebbe utilizzare una funzione reduce() per mappare le coppie chiave-valore a un oggetto.

/** 
 
* Apply to an existing or new object, parallel arrays of key-value pairs. 
 
* 
 
* @param {string[]} keys  - List of keys corresponding to their accociated values. 
 
* @param {object[]} vals  - List of values corresponding to their accociated keys. 
 
* @param {object} [ref={}] - Optional reference to an existing object to apply to. 
 
* 
 
* @returns {object} - The modified or new object with the new key-value pairs applied. 
 
*/ 
 
function toObject(keys, vals, ref) { 
 
    return keys.length === vals.length ? keys.reduce(function(obj, key, index) { 
 
    obj[key] = vals[index]; 
 
    return obj; 
 
    }, ref || {}) : null; 
 
} 
 

 
var keys = [ "height" , "width" ]; 
 
var values = [ "12px" , "24px" ]; 
 

 
document.body.innerHTML = '<pre>' + JSON.stringify(toObject(keys, values), null, 2) + '</pre>';

9

uso lodash.

_.zipObject

Esempio

_.zipObject(['a', 'b'], [1, 2]); 
// ➜ { 'a': 1, 'b': 2 } 
1

Come una soluzione alternativa, non già detto penso:

var result = {}; 
    keys.forEach((key, idx) => result[key] = values[idx]); 
0

strano e brutto ma minuscola

Questo non è il ... diffondere uno ma solo per calci.

let arr1 = ['key1', 'key2', 'key3']; 
let arr2 = ['1', '2', '3']; 
let obj = (((o,a,b)=>(a.forEach((c,i)=>o[c]=b[i])||o)))({}, arr1, arr2); 

https://jsfiddle.net/x78gy4yu/

0

Lo si può fare facilmente usando JS Es 6 nuova funzione:

var keys = [ "height", "width" ]; 

var values = [ "12px", "24px" ]; 

var combineObject = { 
[keys.shift()] : values .shift(), 
[keys.shift()] : values .shift() 
}; 
console.log(combineObject); // { height: '12px', width: '24px' } 
+0

Questo funziona solo se si conosce il numero di chiavi in ​​anticipo – itsadok

+0

sì. Via statica –

Problemi correlati