Reputation: 159
I have a response from the server that is like this:
users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
It's a string not an array like it appear, since I need an array to work on, how I can remove the square backets and then the commas to obtain a normal array? I've tried in this way:
var data = ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
data.replace('[', '').replace(']', '').split(',');
but chaining two .replace()
functions and a split()
isn't the best solution. Can anyone halp me?
Upvotes: 0
Views: 164
Reputation: 1
In short, Here you have provided data in normal string formate not in JSON string formate
var data = 'users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]' var squareBracketData = data.substr(data.indexOf("[")) var array = JSON.parse(squareBracketData) console.log(array)
Some personal advice, Try to send JSON stringify data from the server so it will make your life easy
Example:
var users =["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"] // Stringify data var data = JSON.stringify({users}) console.log("Data") console.log(data) // retrieve data from string var parsedData = JSON.parse(data) var parsedUsers = parsedData.users console.log("parsedUsers") console.log(parsedUsers)
Upvotes: 0
Reputation: 1603
In your example data
is an array.
However, if data
was a string you would convert it to an array like this:
var arr = JSON.parse(data);
Upvotes: 1