【问题标题】:JSON array of objects to single stringJSON对象数组到单个字符串
【发布时间】:2019-11-22 16:44:31
【问题描述】:

我在 Vue JS 中有一个名为 tags 的数据对象,如下所示:

tags: [
    {name: "menu"},
    {name: "red"}
],

目前我可以用这个输出它们

var tags = this.tags;
var tagss = JSON.stringify(tags);
console.log('list of tags:' + tagss);

但它会像这样返回它:

list of tags:[{"name":"menu"},{"name":"red"}]

我希望它像这样返回它们:

list of tags: menu,red

知道怎么做吗?我想要这样的原因是我可以使用标签列表查询我的 API。

提前致谢。

【问题讨论】:

    标签: javascript json vue.js


    【解决方案1】:

    您只需将 js 对象数组转换为字符串,

    方式 1 使用 map & toString 函数

    首先,我们将对象数组转换为索引数组,然后将数组转换为字符串

    在这一行之后 ->var tags = this.tags;

    var tagss = tags.map(function(tag) {
      return tag['name'];
    });
    console.log(tagss);  //output should be [menu,red]
    tagss_string = tagss.toString();
    console.log(tagss_string);  //output should be menu,red
    

    方式 2 仅使用循环并将值连接到字符串

    var tags_string = '';
    for (var i=0;i<tags.length;i++){
        if (i!=0)
        tags_string += ','+tags[i].name ;
        else 
        tags_string += tags[i].name ;
    }
    console.log(tags_string);  //output should be menu,red
    

    【讨论】:

      【解决方案2】:

      您可以使用Array.map 遍历数组并将名称提取到一个新数组中,然后加入项目以创建逗号分隔的字符串,如下所示:

      tags.map(({ name }) =&gt; name).join(', ');

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多