svnm
svnm

Reputation: 24338

map over properties in array and concat a string in JavaScript es6

I have the following array of objects for example some authors and I want to map through them and return a string which has been concatenated with some formatting. I am for some reason having an issue with this fairly easy thing.

const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
let names = authors.map( (a, i) => {
  return `${a.name} is cool`
})
console.log(names)
// ["Steven is cool","Nick is cool"]
// but I really want the string "Steven is cool Nick is cool"

How can I instead get this to map through and format it to a string?

e.g. "Steven is cool Nick is cool"

Upvotes: 9

Views: 29230

Answers (3)

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

i for one prefer the use of reduce

ES5 version

autors.reduce(function (str, person) { 
  return (str+' '+person.name+ ' is cool');
}, ''); 

ES6 version

autors.reduce((str, person) => `${str} ${person.name} is cool`, '');

Upvotes: 5

james emanon
james emanon

Reputation: 11807

Here is another version so you don't have to map --> join.. you can just reduce.

const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]

console.log(authors.reduce( (p,c) => `${p} ${c.name} is cool `, ""))

Upvotes: 1

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93213

Use Array#Join :

authors.map((a) => `${a.name} is cool`).join(' ');

DEMO


NOTE : join is not related to ES6 , it is old .

Upvotes: 30

Related Questions