Search code examples
javascriptlodash

turn a table into an array of objects in JavaScript


I have a table

const header = ["name", "age", "hobby"];
const content = [ ["Eva", 3, "dance"],
                  ["Kevin", 5, "ball"],
                  ...];

How can I get output as an array of objects?

[{name: "Eva", age: 3, hobby: "dance"}, 
 {name: "Kevin", age: 5, hobby: "ball"},
 ...]

Solution

  • Lodash (or underscore.js) library provides some nice functions to transform data. It's just one line:

    import _  from 'lodash';
    const output = content.map((row) => _.zipObject(row, header));