Question

In this example snippet of code, I selectively convert 2 columns from my 2D array into an object. The 1st column represents the keys, the 2nd represents the values.

I feel like there is a more concise way of codifying this idea without so many lines of code.

var my2dArray = [ ['a',2], ['b',3], ['c',4] ];
var keys = [];
var values = [];
var myObj = {};

for(var row = 1; row < my2dArray.length; row++) {
    keys[row] = my2dArray[row][0];
    values[row] = my2dArray[row][1];
    myObj[keys[row]] = values[row];
}

console.log(prod_compare); // outputs object

In reality, I have a 4 column array. Don't mind the simplicity of my2dArray. Is there a way to select these two columns for mapping to an object without having to declare 2 temporary arrays?

Was it helpful?

Solution

Your code is fundamentally OK, but it can be more concise without being obfuscated:

var my2dArray = [ ['a',2], ['b',3], ['c',4] ];
var myObj = {};

for (var i=0, iLen=my2dArray.length; i<iLen; i++) {
  myObj[my2dArray[i][0]] = my2dArray[i][1];
}

OTHER TIPS

This may convert [['a', 1, 2, 3], ['b', 1, 2, 3]] to {a: [1, 2, 3], b: [1, 2, 3]}.

for(var row = 0; row < my2dArray.length; row++) {
    keys[row] = my2dArray[row][0];
    values[row] = my2dArray[row].slice(1);
    myObj[keys[row]] = values[row];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top