rafaelfndev rafaelfndev - 9 months ago 114
jQuery Question

How to change input key name of multi dimensional array with JavaScript/jQuery

I need change input key name (this key name is dynamic), like

name="field[value][status]"
to something like
name="field[my_new_value][status]"
and keeping values os status, name, age, etc...



var all_fields = $('[data-fields]');

var some_field = $(all_fields[2]).find('[name]');
// some_field[0] => fieldname[][status]
// some_field[1] => fieldname[][name]
// some_field[2] => fieldname[][age]

var field_dinamyc = $(all_fields[3]).find('[name]');
// field_dinamyc[0] => fieldname[dynamic_key][status]
// field_dinamyc[1] => fieldname[dynamic_key][name]
// field_dinamyc[2] => fieldname[dynamic_key][age]

console.log(some_field);
console.log(field_dinamyc);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-fields>
<input type="text" name="fieldname[1][status]" value="status field 1" />
<input type="text" name="fieldname[1][name]" value="name field 1" />
<input type="text" name="fieldname[1][age]" value="age field 1" />
</div>

<div data-fields>
<input type="text" name="fieldname[2][status]" value="status field 2" />
<input type="text" name="fieldname[2][name]" value="name field 2" />
<input type="text" name="fieldname[2][age]" value="age field 2" />
</div>

<div data-fields>
<input type="text" name="fieldname[][status]" value="status field no key id" />
<input type="text" name="fieldname[][name]" value="name field no key id" />
<input type="text" name="fieldname[][age]" value="age field no key id" />
</div>

<div data-fields>
<input type="text" name="fieldname[dynamic_key][status]" value="status field any" />
<input type="text" name="fieldname[dynamic_key][name]" value="name field any" />
<input type="text" name="fieldname[dynamic_key][age]" value="age field any" />
</div>




Answer Source

If you want to overwrite the first array name of each group to the group's numeric id in the list, you could use:

$('[data-fields]').each(function(i, fields){
        // Loop over data-fields groups and grab their index
        $('input', fields).each(function(){
                // Rename first array value from name to group index
                $(this).attr('name', $(this).attr('name').replace(/e\[[^\]]*\]/, 'e['+(i+1)+']')); 
            });
    });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download