我正在尝试创建一个对象,该对象将用于发布到事件网格。有一些顶级属性,例如 EventType ,主题, DataVersion 和 EventTime 。但是,我希望提供给req.query的其他任何内容都可以作为子项添加到data属性中。目前,下面的代码仅添加req.query
中的最后一项,而不会继续添加/追加。
let parms = req.query;
for (var i in parms) {
let myKey = i;
let myValue = req.query[i];
switch (i) {
case 'eventtype':
event[0].eventtype = myValue;
break;
case 'subject':
event[0].subject = myValue;
break;
default:
event[0].data = { [myKey]: myValue };
break;
}
}
输出
eventTime: 2019-03-23T13:47:26.069Z,
dataVersion: '2.0',
eventtype: 'build',
subject: 'build' },
data: { color: 'red' } ]
期望的结果
eventTime: 2019-03-23T13:47:26.069Z,
dataVersion: '2.0',
eventtype: 'build',
subject: 'build' },
data: { color: red, power: on }]
答案 0 :(得分:0)
将data
定义为对象,然后将键和值附加到data
。
let parms = req.query;
for (var i in parms) {
let myKey = i;
let myValue = req.query[i];
switch (i) {
case "eventtype":
event[0].eventtype = myValue;
break;
case "subject":
event[0].subject = myValue;
break;
default:
if (event[0].data) {
event[0].data[myKey] = myValue;
} else {
event[0].data = { [myKey]: myValue }
}
break;
}
};
答案 1 :(得分:0)
您还可以尝试使用Object.assign,它将迭代对象的自身属性和必要的新属性。
let parms = req.query;
for (var i in parms) {
let myKey = i;
let myValue = req.query[i];
switch (i) {
case "eventtype":
event[0].eventtype = myValue;
break;
case "subject":
event[0].subject = myValue;
break;
default:
event[0].data = Object.assign(event[0].data, { myKey: myValue });
break;
}
};