user1221765 user1221765 - 1 year ago 99
Javascript Question

Add Property dynamically to the JSON array

I would like to two add property Id and ButtonId to the exisiting json result. I have pasted the below js code for reference and I would like to pass the jsonresult to MVC controller. As of now it returns null. please help to proceed. Thanks.

my final result should look like this

{"Id":"4","ButtonId":"1177","1178","1179"}} etc..

var btnlist = {Groups: {Id:"", ButtonId: ""}};
$.each($(".buttonData"), function (index, value) {
var values =':');
grpid = values[0].split('-')[1];
btnid = values[1].split('-')[1];

console.log('grpid=' + grpid + ' btnid=' + btnid);

if (typeof (btnlist['Groups'][grpid]) == 'undefined') {
btnlist['Groups'][grpid] = [];

type: "POST",
url: "@Url.Action("Home", "Menu")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(btnlist) ,
success: function (result) {
console.log('json' + JSON.stringify(btnlist));
error: function (request, error) {

This is the json result before pushing into the multidimensional array

The json result, where the properties Id and ButtonId is inserted behind.
json result

null result passed to the controller

Answer Source

With assistance of my colleague, the desired output is as below. This is for other programmers who face similar issue with JSON array. Thanks.

         var btnlist = [];
              btngrps = $('.btn-sort-container');
              $.each(btngrps, function(k, v) {
                btnarr = {};

                gid = $(this).attr('id');
                grpid = gid.split('-')[1];
                btnarr.Id = gid.split('-')[1];

                btnobjs = $(v).find('.buttonData');
                if (btnobjs.length) {
                  btnarr['btnId'] = [];
                  $.each(btnobjs, function(bk, bv) {

                    btnid = $(bv).attr('id').split('-')[2];



Output on console


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download