1

How can we put data into multi dimensional array or json within a loop. I know that it's possible to store multi dimensional data at one time, but I want it inside the loop as I have described in the code.

var sub_cat_checked_val = [];    
sub_cat_checked.each(function (index) {
    var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
    sub_cat_checked_val['key_one']['key_two']='value';
    sub_cat_checked_val[sub_cat_id][index] = index:jQuery(this).val();
});

As it's possible in php like $var_name['key1']['key2']['keyn']='value';

1
  • ?.............. Commented Sep 24, 2016 at 22:21

3 Answers 3

1

sub_cat_checked_val[sub_cat_id] needs to be defined as an array, so add the lines:

if (!sub_cat_checked_val[sub_cat_id]) {
    sub_cat_checked_val[sub_cat_id] = [];
}

to define the value as an array if it does not exist.

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

1 Comment

Please remember to format code as code (using either backticks or 4-space/tab indentation)
1

Try this snippet:

<script>
var k = {};
k.a = {};
k.a.b = {};
k.a.b.c = {};
k.a.b.c.d = 5;
console.log(k);
</script>

2 Comments

I want value of the variable should be key like if a=2, then when using k.a='Value' it should return {k:{2:Value}}
With numerical ones it won't work, but you can always add an underscore as a prefix, so for example: k._2._14._21 = 35;
0

I was able to do it with all of you guys help with some of modifications.

Here is what I did:

        sub_cat_checked.each(function (index) {
            console.log(index_val);
            var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
            console.log(sub_cat_id);
            if (sub_cat_checked_val[sub_cat_id] == undefined) {
                sub_cat_checked_val[sub_cat_id] = [];
            }

            sub_cat_checked_val[sub_cat_id][index] = jQuery(this).val();
        });

Thanks a lot to all of you.

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.