PASSWORD RESET

Your destination for complete Tech news

How to convert CSV data into an array in Javascript?

963 0
< 1 min read

To convert CSV data into an array of objects in JavaScript, you can use the split() method to split the CSV data into rows, and then use the map() method and the split() method again to split each row into an array of values.

Here is an example of how to convert CSV data into an array of objects:

const csv = `id,name,email
1,John Smith,[email protected]
2,Jane Doe,[email protected]
3,Bob Johnson,[email protected]`;

const rows = csv.split('\n');
const data = rows.map(row => {
  const values = row.split(',');
  return {
    id: values[0],
    name: values[1],
    email: values[2]
  };
});

console.log(data);
/*
[
  { id: '1', name: 'John Smith', email: '[email protected]' },
  { id: '2', name: 'Jane Doe', email: '[email protected]' },
  { id: '3', name: 'Bob Johnson', email: '[email protected]' }
]
*/

In this example, the CSV data is first split into rows using the split() method and the newline character '\n' as the separator. The resulting array is then passed to the map() method, which splits each row into an array of values using the split() method.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.