0

I have an array that I am taking from backend that is like

["[a,b,c],[c,d,e],[e,f,g]"]

I am taking this array in

<div id="op1">{{$option}}</div> 

now I want to add more items into it when I access it in javascript using

document.getElementById('op1').innerHTML 

and add this into an array

var options=[document.getElementById('op1').innerHTML];

and when I print it using

console.log(options)

it shows me

["[a,b,c],[b,c,d],[e,f,g]"]

type of array other than

[[a,b,c],[b,c,d],[e,f,g]]   

so how I can get this type of array and more items into it.

Kirankumar Dafda
  • 2,354
  • 5
  • 29
  • 56
ksanjay
  • 75
  • 9
  • And what is `[[a,b,c],[b,c,d],[e,f,g]]`? What does it represent, what are `a`, `b`? Are they strings or variables or letters? You would be able to parse if it was a valid JSON, but in this case it is unclear what you want to be stored in your `options` after reading this input. – Yeldar Kurmangaliyev Aug 20 '18 at 12:57
  • 1
    Possible duplicate of [Convert string with commas to array](https://stackoverflow.com/questions/13272406/convert-string-with-commas-to-array) – Mario Santini Aug 20 '18 at 12:58
  • And why don't you also pass it to a javascript variable in a script tag instead of trying to parse it from html text? – charlietfl Aug 20 '18 at 12:59

2 Answers2

1

I am not sure that this answer is optimal solution but I have tried to bring a solution that nearly fits your requirements:

var arr = ["[a,b,c],[b,c,d],[e,f,g]"];
var res = [];
arr[0].split('[').forEach((splitVal) => {
  if (splitVal) {
    var arrInner = [];
    var commaSplit = splitVal.split(',');
    commaSplit.forEach((commaSplitVal) => {
      if (commaSplitVal) {
        arrInner.push(commaSplitVal.replace(']', ''));
      }
    });
    res.push(arrInner);
  }
});
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

The state of your data specified above ["[a,b,c],[c,d,e],[e,f,g]"] is a JS Array with 1 item, which is a string. The string contains a comma separated list of arrays.

You can use String.prototype.split to split the string into arrays by a separator like such

var options=[document.getElementById('op1').innerHTML];
var arrayYouWant = options.map(item => item.split(','));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

parallaxis
  • 196
  • 1
  • 13