Code Lab

CSV to objects

EasyJSON and data6 min

Test data came as a CSV string. Lines are separated by \n, values in a line are separated by commas, and the first line holds the headers. Write a function csvToObjects(csv) that returns an array of objects, one for every data line. The keys come from the headers, and the values stay strings.

Examples

csvToObjects('name,age\nAnn,30\nBob,25')

Returns [ { name: 'Ann', age: '30' }, { name: 'Bob', age: '25' } ]

csvToObjects('id,title')

Returns []

There are only headers and no data.

Asked at Infosys · Source

Loading the editor...
  1. InputcsvToObjects('name,age\nAnn,30\nBob,25')
    Expected[ { name: 'Ann', age: '30' }, { name: 'Bob', age: '25' } ]
  2. InputcsvToObjects('login,role,active\nadmin,owner,true')
    Expected[ { login: 'admin', role: 'owner', active: 'true' } ]
  3. InputcsvToObjects('id,title')
    Expected[]

Hidden tests run on Submit.