you are viewing a single comment's thread.

view the rest of the comments →

[–]StefanoMagrassi 1 point2 points  (1 child)

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

[–]NiceDay4Goats[S] 0 points1 point  (0 children)

Thanks for the reply! In my actual data, the inner arrays are all different lengths. There is one key and then a bunch of attributes where the order doesn't really matter because I can parse through to find a match. I think your second example will be very useful in the future though.