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

javascript - JSON array of objects to single string - Stack Overflow

programmeradmin4浏览0评论

I have a data object in Vue JS called tags that looks like this:

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

Currently I am able to output them with this

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

but it returns it like this:

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

and I want it to return them like this:

list of tags: menu,red

Any idea how to do this? The reason I want it like this is so I can query my API with a list of tags.

Thanks in advance.

I have a data object in Vue JS called tags that looks like this:

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

Currently I am able to output them with this

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

but it returns it like this:

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

and I want it to return them like this:

list of tags: menu,red

Any idea how to do this? The reason I want it like this is so I can query my API with a list of tags.

Thanks in advance.

Share Improve this question asked Jul 12, 2019 at 23:31 user3479267user3479267 23210 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You can use Array.map to iterate over the array and extract the names to a new array, then join the items to create the ma separated string, like so:

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

all you need is just convert js array of objects to a string,

way 1 using map & toString function

so first, we will convert the array of objects to indexed array, then convert array to string

after this line ->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

way 2 just using loop and concatenate values to string

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
发布评论

评论列表(0)

  1. 暂无评论