magicsword magicsword - 3 years ago 206
Javascript Question

Array of Arrays to Dictonary JavaScript

I Have an array of arrays and would like to return a dictionary like so.

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'}


the return dict only returns the last key/value pair. I would like to return all key/value pairs but doing something like dict += {[array[i][0]] : array[i][1]} doesn't work.

Answer Source

You are doing

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

That means you assign a new object to variable dict. Not appending! If you want to append to your dict object. Write this:

dict[array[i][0]] = array[i][1];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download