开发者

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 = {开发者_如何学Go};

    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?


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'] = {...};


You're overriding the same property "alarm" on every iteration.

You should be creating an Array and then push() the values on the end of an Array.

var alarms = [
      {name: 'alarm1'}
    , {name: 'alarm2'}
    , {name: 'alarm3'}
];


var new_alarms = [];


$(alarms).each(function() {
    console.log(this);
    new_alarms.push(this);
});


console.log(alarms, new_alarms);

See: http://jsfiddle.net/y22Hk/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜