Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert an array to an object of key value pairs

if I have an array of strings like:

['person,item,cost,amount',
  'John,shoes,200,2']

how could I convert this into an object that resembles:

{  
   'John':[  
      {  
         item:'shoes',
         cost:'200',
         amount:'2',
         totalPriceForItems:'400'
      }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If I understand correctly, you may try something like this:

const convert = data => {
  const [columnsText, ...items] = data;
  const columns = columnsText.split(',');
  
  return items.reduce((acc, text) => {
    const { person, ...entries } = Object.fromEntries(text.split(',').map((value, i) => [columns[i], value]));
    entries.totalPriceForItems = String(entries.cost * entries.amount);
    
    if(acc[person]) {
      acc[person].push(entries);
    } else {
      acc[person] = [entries];
    }
    
    return acc;
  }, {});
};

const result = convert([
  'person,item,cost,amount', 
  'John,shoes,200,2', 
  'Bob,glasses,50,3',
  'John,shirts,100,5',
]);

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading