0

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();      
});
2
  • This is not a valid array Commented Nov 18, 2022 at 13:40
  • An array is also always an object. For that reason you were able to define the properties like formData["1"]["48"]="1". However, when you convert an array into a JSON string then only the numerically indexed elements will appear in the resulting string. Commented Nov 18, 2022 at 14:00

1 Answer 1

2

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();      
});
Sign up to request clarification or add additional context in comments.

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.