Merge two arrays into key-value pairs
suggest changeObject.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"
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents