0

I read here that the window object can be used to dynamically make a property name within an object. What is the way this is done

I have a function like

function storeValues(){

    var info = {};
    $('.class1').each(function(index1, value1){
        $('.class2', $(this)).each(function(index2, value2){

            //so here I'd like to add a string to the property name
            //like 'param-' and 'detail-' so I could end up with a 
            //structure like 
            //info.param_0.detail_0
            //then
            //info.param_0.detail_1
            //info.param_1.detail_0
            //info.param_1.detail_1
            //info.param_1.detail_2
            info.'param_'index1.'detail_'index2 = $(this).find('.desired_input').val();

    });
}

Is this possible. Or is there a smarter way of doing it?

Community
  • 1
  • 1
1252748
  • 14,597
  • 32
  • 109
  • 229

1 Answers1

7

That has nothing to do with the window, the [] notation for accessing dynamic object property names is an aspect of the JavaScript language.

info['param_' + index1]['detail_' + index2] = $(this).find('.desired_input').val();

Of course, if info['param_' + index1] does not exist yet, you will have to create it as an empty object before setting its properties.

info['param_' + index1] = info['param_' + index1] || {};
info['param_' + index1]['detail_' + index2] = $(this).find('.desired_input').val();
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166