Merge two arrays into key-value pairs

suggest change

Object.fromEntries builds an object from [key, value] pairs. If rows is shorter, the missing value is undefined, and JSON.stringify omits that key. Object.fromEntries has been standard since ES2019.

const columns = ["Date", "Number", "Size", "Location", "Age"];
const rows = ["2001", "5", "Big", "Sydney", "25"];
const result = Object.fromEntries(
  columns.map((column, index) => [column, rows[index]])
);

console.log(JSON.stringify(result, null, 2));
{
  "Date": "2001",
  "Number": "5",
  "Size": "Big",
  "Location": "Sydney",
  "Age": "25"
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents