Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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; } , {} );
}
share|improve this answer
1  
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. –  user2033412 Mar 6 at 16:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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