0

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?

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking that it was a string that was returned inside the JSON response. I'm a newbie developer. Thanks for the help.
0

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)
 
 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.