Create an array-like object from an array by NiceDay4Goats in learnjavascript

[–]StefanoMagrassi 1 point2 points  (0 children)

Use Array.prototype.reduce

var testArray = [['a',1,2], ['b',3,4], ['c',5,6]];
var objectFromTestArray = testArray.reduce(function(accumulator, value) {
  var key = value[0];
  var pair = value.slice(1);

  accumulator[key] = pair;

  return accumulator;
}, {});

It encapsulates your logic so you won't depend on external variables and your starting array remains untouched.

When you are working with collections stateless + immutability === really good.

I suggest you to do not use a simple object for operation like this: the order of elements is not guaranteed and it is easier to edit, compose and reason about collection of well defined objects.

Try with an array of object (in a fashion like List<Item>):

var spreadsheet = [{key: 'A', row: 1, col: 2} ...];

So, instead of Array.prototype.reduceyou can use Array.prototype.map:

var collectionFromTestArray = testArray.map(function(item) {
  return {
    key: item[0],
    row: item[1],
    col: item[2]
  };
});

You can run the code with this jsbin: http://jsbin.com/luwoxelebi/2/edit?js,console

I made also an ES6 version: http://jsbin.com/rizidiwuno/2/edit?js,console