Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON array of objects to single string

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.

like image 998
user3479267 Avatar asked Jan 27 '23 02:01

user3479267


2 Answers

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 comma separated string, like so:

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

like image 88
Jake Avatar answered Jan 28 '23 15:01

Jake


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
like image 36
Omar Tammam Avatar answered Jan 28 '23 15:01

Omar Tammam