convert an array to an object of key value pairs

goatstash

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'
      }
Hao Wu

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);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Convert array to object using array values for object key value pairs

Convert array into key / value pairs

How to convert array to an object with key/value pairs Javascript

Convert array of "key-value" pairs into object using javascript

Convert array of "key-value" pairs into object using javascript

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

How to convert an array into an object in javascript with mapped key-value pairs?

How to convert an array of nested objects to an object with key, value pairs in JavaScript

Convert JavaScript array of 2 element arrays into object key value pairs

Convert array of objects to object of key-value pairs

How to convert an array of objects to object with key value pairs

Array of key/value pairs to object

Convert key/value pairs to object using lodash

Convert Tree of key value pairs to a json object

How to convert string into object with key value pairs

Key value pairs array into array object

Convert string into key-value pairs in an array

Converting an array into an object with key/value pairs

Flatten array of key-value pairs into object

reduce key value pairs in JS Array to object

Map array of objects to object of key value pairs

Convert nested array of objects to object of key-value pairs using reducer

How to convert object containing key-value pairs to an array of objects in JavaScript

convert an array and an array of arrays into array of objects with key value pairs

Convert array to key value object

convert JSON array of key value pairs to JSON Array of strings in Javascript

Convert array of key-value pairs into associative array

Convert Map key,value pairs into JSON properties of a @responseBody object