在Javascript对象中添加动态字段名称的可能性? [英] is it possiblle to add dynamic field name in the Javascript Object?

查看:60
本文介绍了在Javascript对象中添加动态字段名称的可能性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加动态字段名称并根据该值更新值.在我的情况下,eventType有4种类型,即交付,发送,打开,单击.当我尝试使用此代码时,我获得了唯一的eventType作为字符串.

I am trying to add the dynamic field name and update the value according to that.in my case eventType is of 4 types delivery, send, open, click.and when i am trying to use this code i got the only eventType as a string.

 const event = JSON.parse(req.body);
  // const xyz = JSON.parse(JSON.parse(req.body.Message))
  // console.log(xyz)
    const message = JSON.parse(event.Message);
    console.log(message)
    const eventType = message.eventType;


  await db.collection('Emails').doc(message.mail.commonHeaders.to[0]).set(
   { eventType: message,
    timestamp: Date.now(),
  },
  { merge:false },);

这是端点代码,而eventType是我上面提到的事件.

this is an endpoint code and eventType is the event i mentioned above.

推荐答案

可以将动态密钥添加到JSON对象.

Dynamic keys can be added to the JSON object.

示例:

var key = 'age'
var keys = ['name','gender'];
var data = {};

现在,如果您想在运行时决定要使用[]的键,这里有个问题,因为它允许表达式求值.

Now here is a catch if you want to decide the key on runtime you need to use [], because it allows the expression to evaluate i.e.

data[keys[0]] = 'Rohan'
//keys[0] will interpreted to name during the execution
//data ==>> {name:'Rohan'}

data.key = '19'
//"key" will be treated as an individual entity i.e. as a valid key name
//data ==>> {key:'19'}
//whereas
data[key] = '19'
//results in data ==>> {age:'19'}

还要注意,如果您在[]内包装了一个双",它也将被视为一个单独的实体

And also note that if you wrap a double "" inside [] it will also be treated as an individual entity

data['key'] = '19'
// data ==>> {key:'19'}

这篇关于在Javascript对象中添加动态字段名称的可能性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆