-1

Essentially, I would like to make:

var current = [
    [4, 'socks'],
    [2, 'pants'],
    [1, 'shoes'],
    [5, 'hats']
];

Into this:

var current = {
    socks: 4,
    pants: 2,
    shoes: 1,
    hats: 5
};
lfkwtz
  • 1,007
  • 2
  • 11
  • 25
  • Yes, you can! try with a loop if you haven't yet. If you have and weren't happy with the result, post your code and explain where you have problems – Mario Trucco Oct 05 '15 at 22:33

3 Answers3

3

If you want to iterate through a collection and return a single object then reduce() is your tool:

var current = [
    [4, 'socks'],
    [2, 'pants'],
    [1, 'shoes'],
    [5, 'hats']];

current.reduce(
   function(m,c) { 
       m[c[1]] = c[0]; 
       return m;
   }, {})

// Object {socks: 4, pants: 2, shoes: 1, hats: 5}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Malk
  • 11,855
  • 4
  • 33
  • 32
2

You can loop through the arrays in the array and add them as properties in the object:

var result = {};
for (var i = 0; i < current.length; i++) {
  result[current[i][1]] = current[i][0];
}

Demo:

var current = [
    [4, 'socks'],
    [2, 'pants'],
    [1, 'shoes'],
    [5, 'hats']];

var result = {};
for (var i = 0; i < current.length; i++) {
     result[current[i][1]] = current[i][0];
}

// show result in snippet
document.write(JSON.stringify(result));
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

With [].forEach.call():

 var current = [
   [4, 'socks'],
   [2, 'pants'],
   [1, 'shoes'],
   [5, 'hats']
 ];

 var res = {};

 [].forEach.call(current, function(el) {
   res[el[1]] = el[0];
 });

console.log(res);

var html = document.getElementById("result");
result.innerHTML = JSON.stringify(res);
<div id="result"></div>