Skip to content
Advertisement

Convert 2D JS array to json string

My array in variable is:

"1": ["48": '1', "49": '2']
"2": ["51": '3', "52": '4', "53": '5', "54": '6']
"3": ["30": '7']

I’ve mentioned key and value here for the 2D array, I’m trying to convert this to JSON string. I tried JSON.stringify(arraydata), arraydata is the variable where the array is stored, but it makes the string empty, whereas array data is correct.

Edit: This is how I’m adding array data:

var arraydata = new Array();
$('.classselector').each(function(){
    let key1= $(this).data('key1');
    let key2= $(this).data('key2');
    if ( !Array.isArray(arraydata['"'+key1+'"']) ) {
        arraydata['"'+key1+'"'] = new Array();
    }
    arraydata['"'+key1+'"']['"'+key2+'"'] = $(this).val();      
});

Advertisement

Answer

The “array” quoted in your question is not valid JavaScript code. Maybe you had on object of objects instead? In that case the object can easily be converted into a JSON string:

const obj={"1": {"48": '1', "49": '2'},
"2": {"51": '3', "52": '4', "53": '5', "54": '6'},
"3": {"30": '7'}};

console.log(JSON.stringify(obj));

// in case you were really talking about 
// a sparsely populated array of arrays,
// then the solution could look like this:

const arr=[];
arr[1]=[];
arr[1][48]='1';
arr[1][49]='2';
arr[2]=[];
arr[2][51]='3';
arr[2][52]='4';
arr[2][53]='5';
arr[2][54]='6';
arr[3]=[];
arr[3][30]='7';

console.log(arr);
console.log(JSON.stringify(arr));

See my comment above. Use objects instead of arrays!

Your corrected script could look something like this:

var arraydata = {};
$('.classselector').each(function(){
    let key1= $(this).data('key1');
    let key2= $(this).data('key2');
    if ( !arraydata[key1] ) {
        arraydata[key1] = {};
    }
    arraydata[key1][key2] = $(this).val();      
});
Advertisement