2
\$\begingroup\$

I'm writing a simple table-oriented storage for objects. The schema of a table is stored in the columns-array and the data in the rows-array.

// example: table "employees"
var columns = ["id", "name"]
var rows = [[1, "Alice"], [2, "Bob"]];

I wrote a function to convert a row-array into an object:

function convertRowToObject(row) {
    var result = {};
    for (var i = 0; i < columns.length; i++) result[columns[i]] = row[i];
    return result;
}

Now I can get an employee-object where I can access the fields by name, not by index.

// [1, "Alice"] -> { id: 1, name: "Alice" }

Is there any way to get the convertRowToObject function any smaller? I think there should be a way to get rid of the loop and make this with a single line of code.

\$\endgroup\$
2
\$\begingroup\$

You could make it smaller by turning your function into a constructor:

function RowObject(row) {
    for (var i = 0; i < columns.length; i++) 
      this[columns[i]] = row[i];
}

You would have to call this function with new then. I would avoid putting the assignment on the same line as the for, it is too Golfic to maintain.

The only way to avoid a loop is to fake it:

function convertRowToObject2(row) {
  //o -> object, v -> value, i -> index
  return row.reduce( function(o, v, i){ o[columns[i]] = v; return o; } , {} );
}
\$\endgroup\$
  • 1
    \$\begingroup\$ I like the one-liner, but the compiler will not know that he can handle the elements of the array independently, hence I will not be executed in parallel, as it can be done with map for example. \$\endgroup\$ – user2033412 Mar 6 '14 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.