追加到对象

2022-08-30 01:54:52

我有一个对象,其中包含警报和有关它们的一些信息:

var alerts = { 
    1: { app: 'helloworld', message: 'message' },
    2: { app: 'helloagain', message: 'another message' }
}

除此之外,我还有一个变量,上面写着有多少警报。我的问题是,当我去添加新警报时,有没有办法将警报附加到对象上?alertNoalerts


答案 1

如何将警报存储为数组中的记录,而不是单个对象的属性?

var alerts = [ 
    {num : 1, app:'helloworld',message:'message'},
    {num : 2, app:'helloagain',message:'another message'} 
]

然后要添加一个,只需使用:push

alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});

答案 2

jQuery会为你合并2个对象,但你应该真正使用一个数组。$.extend(obj1, obj2)

var alertsObj = {
    1: {app:'helloworld','message'},
    2: {app:'helloagain',message:'another message'}
};

var alertArr = [
    {app:'helloworld','message'},
    {app:'helloagain',message:'another message'}
];

var newAlert = {app:'new',message:'message'};

$.extend(alertsObj, newAlert);
alertArr.push(newAlert);