Code Lab

Mode entretien. Minuteur de 6 min, sans indices ni autocomplétion

CSV to objects

FacileJSON 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.

Exemples

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

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

csvToObjects('id,title')

Renvoie []

There are only headers and no data.

Posé chez Infosys · Source

Chargement de l'éditeur...
  1. EntréecsvToObjects('name,age\nAnn,30\nBob,25')
    Attendu[ { name: 'Ann', age: '30' }, { name: 'Bob', age: '25' } ]
  2. EntréecsvToObjects('login,role,active\nadmin,owner,true')
    Attendu[ { login: 'admin', role: 'owner', active: 'true' } ]
  3. EntréecsvToObjects('id,title')
    Attendu[]

Les tests cachés se lancent à la soumission