Search code examples
javascriptjqueryextend

Extend a JavaScript object


I'm looping inputs in a table, that don't have any form tag. I get the values correctly. I want to build with their values an object that contains multiple objects.

What i'm expecting?

alarms = { alarm: { status_id: '1', alarm_name: 'Critic', user_id_created: '30021061' }, alarm: { status_id: '1', alarm_name: 'Middle', user_id_created: '30021061' }, alarm: { status_id: '1', alarm_name: 'Bottom', user_id_created: '30021061' }, ... };

What i'm getting? The last object in the loop.

alarms = { alarm: { status_id: '1', alarm_name: 'Bottom', user_id_created: '30021061' } };

Here is the code:

var alarms = {}
$('.new_alarm').each(function() {
    var status_id = $(this).children('.status').children().val(),
        alarm_name = $(this).children('.data').children('input[name="alarm_name"]').val(),
        user_id = $('#user_id').text();
        objAux = {};

    if(alarm_name) {            
        objAux = {
            alarm: {
                'status_id': status_id,
                'alarm_name': alarm_name,
                'user_id_created': user_id
            }
        };
    }

    alarms = $.extend(true, alarms, objAux);          
});

What's wrong with the jQuery extend method? Why is not merging the objects?


Solution

  • If I'm not mistaken, what you want is actually impossible. It's akin to saying you want an array to have 5 values for the a[1].

    You could implement this using an array instead of an object:

    alarms = [{...},{...},{...}];
    

    What you're writing is actually this:

    alarms['alarm'] = {...};
    alarms['alarm'] = {...};
    alarms['alarm'] = {...};
    alarms['alarm'] = {...};