0

I've built this variable called DLP. When I'm done doing what i need to do with the page, the variable looks something like this:

[['0','A'],['1','B'],['2','C'] ]

How can I turn this variable into a multi-dimension array so that when i go:

DLP[1][1]

it returns my result?

4
  • 2
    DLP[1][1] will return a result, B. What is your result that you're expecting it to return? Commented Jul 31, 2015 at 21:12
  • I had a similar question to this once. My question and answers may be helpful: stackoverflow.com/questions/29738068/… Commented Jul 31, 2015 at 21:12
  • Do you mean that DLP is a string variable with the content as shown? Please clarify. Commented Aug 1, 2015 at 0:30
  • Exactly! DLP is a string variable that's put together by doing stuff on the page. Commented Aug 1, 2015 at 0:43

3 Answers 3

1

// the data
var dlp = "[['0','A'],['1','B'],['2','C'] ]";

// make it JSON conform
// replace single quotation marks with double quotation marks
dlp = dlp.replace(/'/g, '"');

// parse the JSON string
// get an array
var dlpArray = JSON.parse(dlp);

// use the array
alert(dlpArray[1][1]);

Sign up to request clarification or add additional context in comments.

Comments

1

There are two ways to start an array.

var array = new Array(); or var array = [1, 2, 3]

It is considered bad practice to do it the first way. You can do what you want like this.

var DLP = [['0','A'],['1','B'],['2','C'] ]

DLP[1][1] will return your result.

Comments

0

[['0','A'],['1','B'],['2','C'] ] is already a multi-dimensional array. DLP[1][1] will return 'B' as Tom said in the comments. If you want to get one of the complete arrays (example: if you wanted the array: "2,C" you would only need to reference DLP[3]). See this question for more information on how to work with multidimensional arrays: JavaScript multidimensional array

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.