附加到对象


156

我有一个可以容纳警报和有关警报的信息的对象:

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

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


6
我认为您发布的json有问题:1:{app:'helloworld','message'} => 1:{app:'helloworld',message:'a message'}吗?
Andreas Grech

Answers:


235

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

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

1
该答案希望您知道要添加的警报的ID。好吧,如果您已经知道这一点,那么您只需遵循原始对象格式并执行:alerts[3] = { app: 'hello3', message: 'message 3' }。这样,您可以通过id访问消息:alerts[2] => { app: 'helloworld', message: 'message' }。获取长度则刚:Object.keys(alerts).length(该位与阵列更容易)
马特·

61

jQuery $.extend(obj1, obj2)会为您合并2个对象,但实际上您应该使用数组。

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

jQuery的扩展速度很慢:trevmex.com/post/2531629773/jquerys-extend-is-slow。另外,还有一个错字。$ .extends()应该读为$ .extend()。

错别字很好。在某些情况下$ .extends会有所帮助,但您是对的,应尽可能避免使用它。
–ECTIONTheCode

1
我认为,当您只有一个记录结构而没有括号时,extend()就可以了,对于其余的我都同意
pectorTheCode

39

您可以使用Object.assign()进行此操作。有时您需要一个数组,但是当使用需要单个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"}
} 

编辑:要解决有关获取下一个键的注释,您可以使用Object.keys()函数获取键的数组-有关增加键的示例,请参见Vadi的答案。同样,您可以使用Object.values()获得所有值,并使用Object.entries()获得键值对。

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]

7
这实际上是正确的答案,因为其他人都将对象转换为数组,但是通过这种方式,您将其保留为对象。以作者为例,可能对他来说使用数组更好,但这将是如何附加到对象的答案。
Goran Jakovljevic

2
是的,我同意..有问题的是,没有一个对象数组,而只是一个对象,所以这是一个完美的答案!
Kishan Oza

不过,这是正确的答案。您如何知道要添加新对象的索引?
卡潘

1
这是标题问题的答案。
FistOfFury

11

像指出的其他答案一样,您可能会发现使用数组更容易。

如果不:

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"}
}      

试试吧:

https://jsbin.com/yogimo/edit?js,控制台


如果您删除了警报或跳过了按键,则此操作将无效。您应该添加一些内容,while(alerts[size]) size++;并且可能会重命名sizenewId
直到

11

您可以按如下方式使用传播语法。

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

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

7

现在有了ES6,我们有了一个非常强大的传播运算符(... Object),可以使这项工作非常容易。可以按照以下步骤完成:

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
 }

而已。它将添加您想要的密钥。希望这可以帮助!!


6

您确实应该使用一系列警报建议,否则将添加到您提到的对象中将如下所示:

alerts[3]={"app":"goodbyeworld","message":"cya"};

但是由于您不应该使用文字数字作为名称引用所有内容并使用

alerts['3']={"app":"goodbyeworld","message":"cya"};

或者您可以使其成为对象数组。

访问它看起来像

alerts['1'].app
=> "helloworld"

5

您是否有能力将最外面的结构更改为数组?所以看起来像这样

var alerts = [{"app":"helloworld","message":null},{"app":"helloagain","message":"another message"}];

因此,当您需要添加一个时,只需将其推入阵列即可

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

然后,您将获得一个内置的基于零的索引,用于枚举错误。


2

使用ES6更轻松:

let exampleObj = {
  arg1: {
    subArg1: 1,
    subArg2: 2,
  },
  arg2: {
    subArg1: 1,
    subArg2: 2,
  }
};

exampleObj.arg3 = {
  subArg1: 1,
  subArg2: 2,
};

console.log(exampleObj);

{
arg1: {subArg1: 1, subArg2: 2}
arg2: {subArg1: 1, subArg2: 2}
arg3: {subArg1: 1, subArg2: 2}
}

0

作为替代方案,在ES6中,可以使用传播语法。${Object.keys(alerts).length + 1}返回下一个id警报。

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

alerts = {
  ...alerts, 
  [`${Object.keys(alerts).length + 1}`]: 
  { 
    app: `helloagain${Object.keys(alerts).length + 1}`,message: 'next message' 
  } 
};

console.log(alerts);


0

抱歉,由于我的声誉,我已经无法评论您的答案!...因此,如果您想修改对象的结构,则必须像Thane Plummer所说的那样,但是如果您不在乎哪里,可以使用一些技巧放置物品:如果您没有指定插入的编号,它将被插入第一个位置。

如果您想将一个Json对象传递给mongoDB函数调用,并在收到的条件内插入一个新键,这将是很棒的。在这种情况下,我将插入代码myUid以及代码中变量中的一些信息:

// From backend or anywhere
let myUid = { _id: 'userid128344'};
// ..
// ..

  let myrequest = { _id: '5d8c94a9f629620ea54ccaea'};
  const answer = findWithUid( myrequest).exec();

// ..
// ..

function findWithUid( conditions) {
  const cond_uid = Object.assign({uid: myUid}, conditions);
  // the object cond_uid now is:
  // {uid: 'userid128344', _id: '5d8c94a9f629620ea54ccaea'}
  // so you can pass the new object Json completly with the new key
  return myModel.find(cond_uid).exec();
}


0

[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唯一不同的是日期和时间。


-1

试试这个:

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

效果很好,它将添加到数组的开头。


这是行不通的,因为我无法在对象上调用拼接,只能在数组上调用。
理查德·伍尔夫
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.