Combining two arrays to form a javascript object

You could as well do this in a more data-centric manner:

const columns = ["Date", "Number", "Size", "Location", "Age"]

const rows = [
  ["2001", "5", "Big", "Sydney", "25"],
  ["2005", "2", "Med", "Melbourne", "50"],
  ["2012", "20", "Huge", "Brisbane", "80"]
]

const result = rows.map(row =>
  row.reduce(
    (result, field, index) => ({ ...result, [columns[index]]: field }),
    {}
  )
)

console.log(result)

UPDATE 2022: Using a now more common syntax (short functions)

Here’s the original snippet:

var columns = ["Date", "Number", "Size", "Location", "Age"];

var rows = [
  ["2001", "5", "Big", "Sydney", "25"],
  ["2005", "2", "Med", "Melbourne", "50"],
  ["2012", "20", "Huge", "Brisbane", "80"]
];

var result = rows.map(function(row) {
  return row.reduce(function(result, field, index) {
    result[columns[index]] = field;
    return result;
  }, {});
});

console.log(result)

This way you would not have to deal with the temporary arrays.

In case your code should work on ancient browsers as well, I’d recommend to take a look at lodash for using map + reduce.

Leave a Comment