Soheil Alizadeh
Soheil Alizadeh

Reputation: 3066

How to Fetch an array of strings in javascript?

I get a list of tag names from the server and fill getedTags with data. my problem is data that it is a type of string while it must be an array , data value: "["HTML","CSS"]" but i need ["HTML","CSS"] how can i fetch an array of strings and add to getedTags variable?

var getedTags = [];
$.get(getTagurl,
    function (data) {

        getedTags = data;

    });

Upvotes: 2

Views: 2200

Answers (3)

keligijus
keligijus

Reputation: 103

You need to use JSON.parse()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

It will make a javascript object or array out of string.

var getedTags = JSON.parse(data)

To reverse this, you can use JSON.stringify() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

It will turn your array or javascript object into a string.

Upvotes: 1

Anurag Singh Bisht
Anurag Singh Bisht

Reputation: 2753

You should convert the data you get from server into array. I presume the data type you are getting is JSON.

You can do JSON.parse(data) to convert in Object.

Upvotes: 2

atiq1589
atiq1589

Reputation: 2327

You can use JSON.parse() from parse string to object.

var getedTags = [];
$.get(getTagurl,
function (data) {
    getedTags = JSON.parse(data);
});

Upvotes: 5

Related Questions