Reputation: 1
I have this array of objects:
let authors = [
{ firstName: "Beatrix", lastName: "Potter" },
{ firstName: "Ann", lastName: "Martin" },
];
I want to unify the details after mapping the array items with map()
, then reduce the objects to a single string with reduce()
so the output would be "Beatrix Potter", "Ann Martin"
.
I have tried the following code but failed:
fullAuthorNames = authors.map( (e)=>
authors.reduce( (firstName, lastName)=> firstName + lastName );
);
This is the relevant output:
["[object Object][object Object][object Object][object Object][object Object]","[object Object][object Object][object Object][object Object][object Object]"
What did I do wrong here? Maybe I didn't target the objects inside the array right?
Upvotes: 3
Views: 80
Reputation: 2302
Array.Map converts an array to another array. Array.Reduce aggregates an array into a value. They're typically used in serial.
Try:
fullAuthorNames = authors.map( (e)=> e.firstName + ' ' + e.lastName )
.reduce((accumulator, currentValue, index) =>
accumulator + (index ? ', ' : '') + currentValue, '');
'join', as in the answers above is probably simpler, but not quite what you asked.
Upvotes: 0
Reputation: 31692
You won't need a reduce
, just map
then join
the result array:
let fullAuthorNames = authors.map(a => a.firstName + " " + a.lastName).join(", ");
Example:
let authors = [
{ firstName: "Beatrix", lastName: "Potter" },
{ firstName: "Ann", lastName: "Martin" },
];
let fullAuthorNames = authors.map(a => a.firstName + " " + a.lastName).join(", ");
console.log(fullAuthorNames);
Upvotes: 4
Reputation: 191976
Map the each object to a string using a template literal, and join the results to a string:
const authors = [
{ firstName: "Beatrix", lastName: "Potter" },
{ firstName: "Ann", lastName: "Martin" },
];
const result = authors.map(({ firstName, lastName }) => `${firstName} ${lastName}`)
.join(', '); // remove this if you want an array of strings
console.log(result);
Upvotes: 0