2

JSON Data sample:

 { 
        "GroupA": "Array[37]", 
        "AGroupC": "Array[9]", 
        "GroupB": "Array[12]", 
        "GroupE": "Array[15]", 
        "GroupF": "Array[21]", 
        "GroupD": "Array[6]" 
        }

I have the above data and I need to convert it to two dimensional array but don't know how to do it. Any help will be appreciated. The resulting should look like:

["GroupA", "GroupC", "AGroupB", "GroupE", "GroupF", "GroupD"]
[37, 9, 12, 15, 21, 6]

Thanks.

4
  • 1
    Do you want a 2D array, or just 2 arrays? Commented Sep 21, 2015 at 19:45
  • I suggest a for-in in addition to a regex. Commented Sep 21, 2015 at 19:45
  • It's a little unclear what the original JSON has... Is it an array that contains only the single numbers specified? Commented Sep 21, 2015 at 19:47
  • You want to convert it then to [ [ key1, key2, ... , keyN ], [ key1.length, key2.length, ... , keyN.length] ] that is all that I'm able to gather from your representation Commented Sep 21, 2015 at 19:48

3 Answers 3

1

Try this:

var dataJson = {
  "GroupA": "Array[37]",
  "AGroupC": "Array[9]",
  "GroupB": "Array[12]",
  "GroupE": "Array[15]",
  "GroupF": "Array[21]",
  "GroupD": "Array[6]"
};

var groupArr = [];
var arrayArr = [];

for (var i in dataJson) {
  if (dataJson.hasOwnProperty(i)) {
    groupArr.push(i);
    arrayArr.push(dataJson[i].match(/\d+/)[0]);
  }
}
alert('groupArr: ' + JSON.stringify(groupArr));
alert('arrayArr: ' + JSON.stringify(arrayArr));

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

1 Comment

Thanks Rayon, this gives back the format I was looking for.
0

From what I can tell, this is what you are asking for.

function convertJSONto2D(json) {
    var 2dArray = [];
    var result  = [];

    2dArray.push(Object.keys(json));

    for(key in json) {
        if (object.hasOwnProperty(key)) {
            result.push(json[key].length);
        }
    }

    2dArray.push(result);

    return 2dArray;
}

Comments

0

Try sometihing like this:

    var dataJson = { 
            "GroupA": "Array[37]", 
            "AGroupC": "Array[9]", 
            "GroupB": "Array[12]", 
            "GroupE": "Array[15]", 
            "GroupF": "Array[21]", 
            "GroupD": "Array[6]" 
            }


    var groupArr = [];
    var arrayArr = [];

    function dataArr() {

        for (i = 0; i < (dataJson.length); i++) {
            groupArr.push(dataJson[i+i]);
            arrayArr.push(dataJson[i+1]);
        }   
    }

//output of each:
//groupArr
// ["GroupA", "GroupC", "AGroupB", "GroupE", "GroupF", "GroupD"]
//arrayArr
// ["Array[37]", "Array[9]", "Array[12]", "Array[15]", "Array[21]", "Array[6]"]

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.