【问题标题】:How to return comma delimited string from array, in React, javascript?如何从数组中返回逗号分隔的字符串,在 React,javascript 中?
【发布时间】:2021-06-29 12:27:25
【问题描述】:

我有这样的数组

const users = [{
  "name": "John",
  "color": "blue",
},{
  "name": "Tim",
  "color": "red",
},{
  "name": "Mike",
  "color": "green",
}]

我想返回结果为

str = "John",Tim","Mike"

但是当我使用时

const str = users.map(item => item.name).join(', ');

我是这样的

str = "John,Tim,Mike"

【问题讨论】:

  • 你的意思是你真的想要"John","Tim","Mike" 在实际的变量值中?
  • 是的,我想要 "John","Tim","Mike" 而不是 "John,Tim,Mike" @Terry
  • const str = `"${users.map(x => x.name).join('", "')}"`;
  • 这会给你想要的结果吗?:const str = users.map(item => `"${item.name}"`).join(', ');
  • @sss 添加为答案,并附有解释。

标签: javascript json reactjs


【解决方案1】:
const str = `"${users.map(x => x.name).join('", "')}"`;

它使用template string 来给出前导和尾随引号,中间是连接数组。不打高尔夫球:

let str = '"'; // prepend "
str += users
  .map(x => x.name) // get the name from the user objs
  .join('", "') // join with the double quote and comma

str += '"'; // closing "

【讨论】:

    【解决方案2】:

    我会使用 reduce 函数,因为它用于将数组缩减为单个输出。如果它是第一项(索引 == 0),则只需将名称返回到累加器(哪种存储字符串并在您遍历数组时附加到它),两边都有引号(用 \ 转义但如果使用单引号则不需要),否则返回累加器,其后带有逗号和引号以及名称和另一个引号。

    所以当你遍历数组时,累加器将是这样的:

    •  
    • “约翰”
    • “约翰”,“蒂姆”
    • “约翰”、“蒂姆”、“迈克”

    当它到达末尾时,它会将它返回给变量,所以commaSeparatedString == "\"John\",\"Tim\",\"Mike\""

    const users = [{
      "name": "John",
      "color": "blue",
    }, {
      "name": "Tim",
      "color": "red",
    }, {
      "name": "Mike",
      "color": "green",
    }];
    
    
    const commaSeparatedString = users.reduce(function(accumulator, currentValue, index) {
      return index == 0 
        ? '\"' + currentValue.name + '\"'
        : accumulator + ',\"' + currentValue.name + '\"';
    }, '');
    
    console.log(commaSeparatedString);

    【讨论】:

    • 你可以简单一点:users.reduce((acc, {name}) => acc ? `${acc}, "${name}"` : `"${name}"`, '')。由于空字符串是错误的,因此您可以检查累加器值而不需要索引,并且可以使用解构来提取名称。
    • 很好,感谢@JaredSmith,这更干净了!
    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 2020-12-27
    • 2020-10-27
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多