arul.k
arul.k

Reputation: 69

create dynamic multi-dimenstional associative array using javascript

Below is my JS code :

        var checkedLength = $(ele).parent().parent().find('table').find(':checkbox:checked').length;

    if(checkedLength)
{
     $(ele).parent().parent().find('table').find(':checkbox:checked').each(function(i) {
        $(this).parent().removeClass().addClass('play');
        $(this).prop('checked',false);
        var agn = $(this).data('agn');
        var value = $(this).data('kid');

        checkedValues[agn] = {};
        // Make bar an array, if it's not defined yet
        checkedValues[agn]["bar"] = checkedValues[agn]["bar"] || [];
        checkedValues[agn]["bar"].push(value);
    });
            console.log(checkedValues);
}

From above code am getting output as :

   object {agnName => bar[0] = 6}

Desired O/P :

   object {agnName => bar[0] = 4,bar[1] = 5 , bar[2]=> 6}

Can anyone guide me how can achieve this array structure ??

Thanks.

Upvotes: 0

Views: 3235

Answers (4)

Amitkumar solanki
Amitkumar solanki

Reputation: 391

To create a mulch-dimensional obj. you have to initialize obj and then you can enter value. like below

var obj = {}

obj[dynamicval1] = {};
obj[dynamicval1][dynamicval2] = {};
obj[dynamicval1][dynamicval2] = {key1:value1,key2:value2};

Hope it works!

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71908

You want an object, not an array:

checkedValues = {};
checkedValues.foo = {};
checkedValues.foo.bar = 'baz';  

// Another way:
checkedValues["keyname"] = "value";

// You can also use variables as keys
var agn = "foo";
checkedValues[agn] = "value";

// Just don't forget to init nested objects
var agn = "foo";
checkedValues[agn] = {};
checkedValues[agn]["bar"] = "value";

// If you need an array inside:
var agn = "foo";
checkedValues[agn] = {};
// Make bar an array, if it's not defined yet
checkedValues[agn]["bar"] = checkedValues[agn]["bar"] || [];
checkedValues[agn]["bar"].push("value");

Upvotes: 3

charlietfl
charlietfl

Reputation: 171679

You have a test to see if checkedValues[agn] exists and you create it as an empty object if it doesn't. However you then immediately try to push to an array within that object that doesn't exist

Try changing

checkedValues[agn] = {};
checkedValues[agn]['pl'].push = $(this).data('kid');

To

checkedValues[agn] = {pl:[]};/* add property "pl" who's value is empty array*/
 /* now the array exists , can push elements into it*/
checkedValues[agn]['pl'].push($(this).data('kid'));

Also note push() syntax you are using is incorrect.....should be push( value )

Upvotes: 3

milks
milks

Reputation: 314

associative arrays are done as objects in Javascript:

var data = {
    agnName: {
        pl: [4, 5, 6]
    }
}

so you can access data.agnName.pl[0] to return 4 or more dynamically with data['agnName'].pl[0]

Upvotes: 0

Related Questions