MisterniceGuy
MisterniceGuy

Reputation: 1796

Map Reduce array to string

I have a array map function which helps me reduce an array of objects down to a simple string.

const formatEmails: (arr: { "default" : string }[]) => string = (arr: { "default" : string }[]) => 
arr.map(e => e["default"]).reduce((e, i) => e + i + "; ", "");

this outputs me the actual email address with out the default. But what if my email looks like this and does not only have default as a key ?

 person_emails: [{ "default": '[email protected]' }, { "home": '[email protected]' }, { "work": '[email protected]' }]

How would i go about that and how can i generate a string of for example "default:[email protected]; home:[email protected]; work:[email protected]"

Also just to be clear my code calls the function formatEmails everytime we read a row on the data export like this

args.rowData["person_emails"] = formatEmails(args.rowData["person_emails"]);

Upvotes: 0

Views: 186

Answers (1)

baao
baao

Reputation: 73241

Simply join the object entries

const person_emails = [{ "default": '[email protected]' }, { "home": '[email protected]' }, { "work": '[email protected]' }];
const res = person_emails.map(e => 
  Object.entries(e).map(en => en.join(':')).join('; ')
).join('; ');
console.log(res);

Above works also for multiple pairs in a single object

Upvotes: 1

Related Questions