Javascript 附加到对象的

Javascript 附加到对象的,javascript,Javascript,我有一个对象,其中包含警报和有关警报的一些信息: var alerts = { 1: { app: 'helloworld', message: 'message' }, 2: { app: 'helloagain', message: 'another message' } } 除此之外,我还有一个变量,表示有多少警报,alertNo。我的问题是,当我要添加新警报时,是否有方法将警报附加到警报对象上?如何将警报存储为数组中的记录,而不是单个对象的属性 var alerts

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

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

除此之外,我还有一个变量,表示有多少警报,
alertNo
。我的问题是,当我要添加新警报时,是否有方法将警报附加到
警报
对象上?

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

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'});

您是否能够将最外层的结构更改为阵列?看起来是这样的

var alerts = [{"app":"helloworld","message":null},{"app":"helloagain","message":"another message"}];
因此,当您需要添加一个时,您可以将其推送到阵列上

alerts.push( {"app":"goodbyeworld","message":"cya"} );

然后,您就有了一个内置的从零开始的错误枚举索引。

您真的应该使用警报建议数组,否则添加到您提到的对象将如下所示:

alerts[3]={"app":"goodbyeworld","message":"cya"};
但是,既然你不应该用字面数字作为名字,那么你就应该引用所有的东西,并用它来命名

alerts['3']={"app":"goodbyeworld","message":"cya"};
或者可以将其设置为对象数组

看起来像

alerts['1'].app
=> "helloworld"
试试这个:

alerts.splice(0,0,{"app":"goodbyeworld","message":"cya"});
工作得很好,它会将它添加到数组的开头。

jQuery
$。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);

正如其他答案所指出的,您可能会发现使用数组更容易

如果没有:

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

// Get the current size of the object
size = Object.keys(alerts).length

//add a new alert 
alerts[size + 1] = {app:'Your new app', message:'your new message'}

//Result:
console.log(alerts)
{ 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
    3: {app: "Another hello",message: "Another message"}
}      
试试看:

您可以使用。有时您需要一个数组,但在处理需要单个JSON对象的函数时(例如OData调用),我发现这种方法比创建一个数组来解包要简单

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

alerts = Object.assign({3: {app:'helloagain_again',message:'yet another message'}}, alerts)

//Result:
console.log(alerts)
{ 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
    3: {app: "helloagain_again",message: "yet another message"}
} 
编辑:为了处理关于获取下一个键的注释,您可以使用函数获取一个键数组——有关增加键的示例,请参见Vadi的答案。类似地,您可以使用获取所有值和键值对


作为替代,在ES6中,可以使用扩展语法
${Object.keys(警报).length+1}
返回警报的下一个
id

让警报={
1:{app:'helloworld',message:'message'},
2:{app:'helloagain',message:'other message'}
};
警报={
…警报,
[`${Object.keys(警报).length+1}`]:
{ 
应用程序:`helloagain${Object.keys(alerts).length+1}`,消息:“下一条消息”
} 
};

控制台日志(警报)您可以使用如下排列语法

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

alerts = {...alerts, 3: {app: 'hey there', message: 'another message'} }

现在使用ES6,我们有一个非常强大的扩展操作符(…对象),它可以使这项工作非常简单。可按如下方式进行:

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

//now suppose you want to add another key called alertNo. with value 2 in the alerts object. 

alerts = {
   ...alerts,
   alertNo: 2
 }
就这样。它将添加您想要的密钥。希望这有帮助

使用ES6更容易:

让exampleObj={
arg1:{
第1部分:1,
第二组:2,
},
arg2:{
第1部分:1,
第二组:2,
}
};
示例OBJ.arg3={
第1部分:1,
第二组:2,
};

console.log(例如obj)很抱歉,由于我的声誉,我不能评论你的答案!。。。因此,如果你想修改对象的结构,你必须像Thane Plummer所说的那样做,但是如果你不在乎项目放在哪里,有一个小技巧:如果你不指定插入的数字,它将被插入到第一个位置

如果您想将一个Json对象(例如)传递给mongoDB函数调用,并在接收到的条件中插入一个新的键,那么这将是非常棒的。在本例中,我将插入一个项目myUid,其中包含代码中某个变量的一些信息:

//从后端或任何位置
让myUid={u id:'userid128344'};
// ..
// ..
让我的请求={u id:'5d8c94a9f629620ea54ccaea'};
const answer=findWithUid(myrequest.exec();
// ..
// ..
函数findWithUid(条件){
const cond_uid=Object.assign({uid:myUid},条件);
//对象条件现在是:
//{uid:'userid128344','u id:'5D8C94A9F629620EA54CCEAA'}
//因此,您可以使用新键完整地传递新对象Json
返回myModel.find(cond_uid.exec();

}
[Javascript]在玩了一点小把戏之后,这对我来说很有效:

 let dateEvents = (
            {
                'Count': 2,
                'Items': [
                    {
                        'LastPostedDateTime': {
                            "S": "10/16/2019 11:04:59"
                        }
                    },
                    {
                        'LastPostedDateTime': {
                            "S": "10/30/2019 21:41:39"
                        }
                    }
                ],
            }
        );
        console.log('dateEvents', dateEvents);

我需要解决的问题是,我可能有任意数量的事件,它们都有相同的名称:LastPostedDateTime不同的是日期和时间

我认为您发布的json有问题:1:{app:'helloworld','message'}=>1:{app:'helloworld',message:'a message'}?JQuery的扩展速度很慢:。还有一个输入错误。$。extends()应为$.extend()。拼写正确。在某些情况下,$.extends是有帮助的,但你是对的,在可能的情况下应该避免使用它。我认为extend()是可以的,因为你只有一个记录结构,没有括号,其余的我同意各自的代码,只需使用push()这不起作用,因为我无法在对象上调用splice,仅在数组上。这实际上是正确的答案,因为其他人指的是将对象转换为数组,但这样您就可以将其保留为对象。在作者的例子中,对他来说使用数组可能更好,但这将是关于如何附加到对象的答案。是的,我同意..问题中没有对象数组,它只是一个对象,所以这是完美的答案!这是正确的答案;您如何知道要添加新对象的索引?这是标题问题的答案。此答案希望您知道要添加的警报的id。好吧,如果您已经知道了,那么您可以简单地按照原始对象格式执行:
alerts[3]={app'hello3',message'message3'}
。使用此功能,您可以通过id访问消息:
alerts[2]=>{app:'helloworld',message:'message'}
。获取长度只需:
Object.keys(alerts).length
(这一点在数组中更容易实现)如果您删除了警报或跳过了一个键,这将不起作用。您应该按照
while(警报[size])size++的行添加一些内容
并可能将
size
重命名为
newId
 let dateEvents = (
            {
                'Count': 2,
                'Items': [
                    {
                        'LastPostedDateTime': {
                            "S": "10/16/2019 11:04:59"
                        }
                    },
                    {
                        'LastPostedDateTime': {
                            "S": "10/30/2019 21:41:39"
                        }
                    }
                ],
            }
        );
        console.log('dateEvents', dateEvents);