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.
1 Answer 1
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; } , {} );
}
-
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– user20334122014年03月06日 16:06:28 +00:00Commented Mar 6, 2014 at 16:06