Skip to content Skip to sidebar Skip to footer

How To Make Object Of Comma Separated Elements

I am working on a CSV parser, where I have data in array like ['Jonas', 'Sched ', 'jonas@sch.com', 'ph:34988934', 'data 1,data 2', 'data 3,data 4', 'data 5, data 6'] What I want t

Solution 1:

Your first step is to pull things out of your original array. This can be done through a destructuring assignment:

const [name, company, email, phone, ...itemCsvs] = yourOriginalArray;

Notice the ...itemCsvs; that destructures anything remaining after the first four items into an array with the variable name itemCsvs.

Each item in itemCsvs looks like comma-separated pairs. You can use the split method of those strings to convert them to string arrays:

const itemPairs = itemCsvs.map(str => str.split(','));

itemPairs is now an array of string arrays.

[
  ["data1", "data2"],
  ["data3", "data4"],
  ["data5", "data6"]  
]

Converting these into objects is then as simple as mapping again:

const items = itemPairs.map(([name, temp]) => ({ name, temp }));

Now you just reassemble the pieces. To put things together more compactly:

const originalData = [
  "Jonas", "Sched ", "jonas@sch.com", "ph:34988934",
  "data 1,data 2", "data 3,data 4", "data 5, data 6"
];

const [name, company, email, phone, ...itemCsvs] = originalData;

const result = {
  name, company, email, phone,
  items: itemCsvs.map(item => {
    const [name, temp] = item.split(',');
    return { name, temp };
  })
};

console.log(result);

Post a Comment for "How To Make Object Of Comma Separated Elements"