0

I am getting a set of Arrays in string format from Database like

["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]

Now I need to load them into array to make an array of arrays. Using this code

        let imgIndicators = [];
        imgIndicators.push( obj[i]['dicatorsbg']);
        console.log(imgIndicators);

is creating an array like

["["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]"]

which as you can see is big long string item, so I tried splitting the data by , like

imgIndicators.push( obj[i]['dicatorsbg'].split(','));

This time code is accepting all , and creating an array of 6 string elemet like

 ["["#464b4e"", ""#7ebcbd"]", " ["#747493"", ""#f5f6f7"]", " ["#58383c"", ""#8d8566"]"]

How can I fix this code to create something like this?

 [
   ["#464b4e", "#7ebcbd"], 
   ["#747493", "#f5f6f7"], 
   ["#58383c", "#8d8566"]
]
4
  • do you get a JSON string or some other format? where is 'dicatorsbg' coming from? Commented Jul 3, 2019 at 6:57
  • I guess it is JSON string because I have this in my PHP side echo json_encode($products); Commented Jul 3, 2019 at 6:58
  • Since it's a JSON (assuming $product is an array-like or object-like in php), please just follow this: 1) Post an example of the JSON, even the original one, if you can share it. 2) Post the expected result. It's not a great deal, it's just matter of parsing the JSON string, acquiring the desired value and pushing it to a new array, that's it. Commented Jul 3, 2019 at 7:00
  • does JSON.parse works for you or just taking the string as is into the javascript part? - with maybe wrapped into brackets? but if the last part is necessary, you do not have a valid JSON. Commented Jul 3, 2019 at 7:00

2 Answers 2

2

If you are really sure that the format will be correct, you can try:

imgIndicators = JSON.parse("[" + obj[i]['dicatorsbg'] + "]");
Sign up to request clarification or add additional context in comments.

Comments

0

Its easy , You have to use JSON.parse() as shown below, shall give you your required result.

//your db output string 
var yourStringArray = '["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]' ; 

// the array you want
var requiredArray = JSON.parse("[" + yourStringArray + "]");

More solutions can be found on this thread issue : Elegant way to convert string of Array of Arrays into a Javascript array of arrays

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.