最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

map over properties in array and concat a string in JavaScript es6 - Stack Overflow

programmeradmin1浏览0评论

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"

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"

Share Improve this question edited Jul 21, 2016 at 6:31 thefourtheye 239k53 gold badges465 silver badges500 bronze badges asked Jul 21, 2016 at 6:13 svnmsvnm 24.3k23 gold badges94 silver badges109 bronze badges 2
  • Your brwoser , and its version ? – Abdennour TOUMI Commented Jul 21, 2016 at 6:15
  • Just names.join(" ")? – Bergi Commented Jul 21, 2016 at 6:45
Add a comment  | 

3 Answers 3

Reset to default 30

Use Array#Join :

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

DEMO


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

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`, '');

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 `, ""))
发布评论

评论列表(0)

  1. 暂无评论