2017-10-01 8 views
0

J'ai un tableau de tableaux et voudrais retourner un dictionnaire comme ça.Tableau de tableaux à Dictonary JavaScript

function retFunc(array) { 
var dict ={}; 
for(var i=0; i<=array.length-1;i++){ 
dict={[array[i][0]] : array[i][1]} 
} 
return dict 
} 

retFunc([['a','b'],'['c','d']]) 

output 
{ c : 'd'} 

La commande de retour renvoie uniquement la dernière paire clé/valeur. Je voudrais retourner toutes les paires clé/valeur mais faire quelque chose comme dict + = {[tableau [i] [0]]: tableau [i] [1]} ne fonctionne pas.

+0

Vous semblez avoir une faute de frappe – mplungjan

Répondre

1

Vous faites

dict={[array[i][0]] : array[i][1]} 

Cela signifie que vous attribuez un nouvel objet à dict variable. Pas d'ajout! Si vous souhaitez ajouter à votre objet dict. Écrire ceci:

dict[array[i][0]] = array[i][1]; 
0

vous devez faire

function retFunc(array) { 
 
var dict ={}; 
 
for(var i=0; i<=array.length-1;i++){ 
 
dict[array[i][0]] = array[i][1]; 
 
} 
 
return dict 
 
} 
 

 
console.log(retFunc([['a','b'],['c','d']]))

0

Utilisez plutôt dict[array[i][0]] = array[i][1]; pour cartographier toutes les valeurs clés.

function retFunc(array) { 
 
var dict ={}; 
 
for(var i=0; i<=array.length-1;i++){ 
 
dict[array[i][0]] = array[i][1]; 
 
} 
 
return dict 
 
} 
 

 
var x = retFunc([['a','b'],['c','d']]); 
 

 
console.log(x);

0

affectation Utiliser comme dict[array[i][0]] = array[i][1] pour ajouter une paire key:value à votre dict Object

Retirez la faute de frappe et du tableau.

function retFunc(array) { 
 
    var dict = {}; 
 
    for (var i = 0; i <= array.length - 1; i++) { 
 
    dict[array[i][0]] = array[i][1] 
 
    } 
 
    return dict 
 
} 
 

 
console.log(retFunc([ 
 
    ['a', 'b'], 
 
    ['c', 'd'] 
 
]))

0

Essayez comme ça avec object affectation clé = valeur,

function retFunc(array) { 
 
    var dict = {}; 
 
    for (var i = 0; i <= array.length - 1; i++) { 
 
    dict[array[i][0]] = array[i][1]; 
 
    } 
 
    return dict; 
 
} 
 

 
console.log(retFunc([ 
 
    ['a', 'b'], 
 
    ['c', 'd'] 
 
]));

0

Vous pouvez utiliser une affectation directe à la clé désirée.

dict[array[i][0]] = array[i][1]; 

function retFunc(array) { 
 
    var dict = {}; 
 
    for (var i = 0; i <= array.length - 1; i++) { 
 
      dict[array[i][0]] = array[i][1]; 
 
    } 
 
    return dict; 
 
} 
 

 
console.log(retFunc([['a', 'b'], ['c', 'd']]));

Une approche plus fonctionnelle pourrait inclure

function retFunc(array) { 
 
    return Object.assign(...array.map(([k, v]) => ({ [k]: v }))); 
 
} 
 

 
console.log(retFunc([['a', 'b'], ['c', 'd']]));

1

Il est très simple avec Object.assign, .map(), spread syntax et paramètre destructuration:

function retFunc(arr) { 
 
    return Object.assign({}, ...arr.map(([k, v]) => ({[k]: v}))); 
 
} 
 

 
console.log(retFunc([['a','b'],['c','d']]));

0

Ceci est un candidat parfait pour la fonction Array.reduce. Voici un exemple commenté qui montre comment fonctionne Array.reduce pour votre exemple. Vous pouvez également trouver de la documentation à MDN

const input = [ 
 
    ['a', 'b'], 
 
    ['d', 'd'], 
 
    ['e', 'f'], 
 
]; 
 

 
// adds key/value from `arr` to dict. 
 
function arrayToDict(dict, arr){ 
 
    dict = dict || {}; 
 
    // take an array of two items and turn it into a key value pair. 
 
    let [key, value] = arr; 
 
    // if you don't like es6 syntax, then this is equivalent 
 
    /* 
 
    var key = arr[0]; 
 
    var value = arr[1]; 
 
    */ 
 
    
 
    dict[key] = value; 
 
    return dict; 
 
} 
 

 
// this function can be used to add any one of our pairs to a dictionary 
 

 
console.log('Example1: ', arrayToDict({}, ['a', 'b'])); 
 

 
// now we can use the Array Reduce function to add each pair to the dictionary. 
 

 
let output = input.reduce(arrayToDict, {}); 
 
console.log('Output:', output);