[英]ES6: How can you add a property (which itself is an object) to an object conditionally only if that property exists
我正在关注这个很棒的教程,根据条件向 object 添加(或不添加)属性。
例如:
{ id: 'some-id', ...(true && { optionalField: 'something'})}
但就我而言,我有一个 object,它看起来像这样:
我想做的是如果12-AM
属性存在,不要覆盖它,添加到它的属性中,这是一个名为message
的键,它是一个数组
如果它没有添加新的时间密钥,即1230-AM
到April-9-2020
这就是我现在所拥有的:
{
...dayInfoInChild,
[currentDate]: { /* April-9-2020 */
[timeOfDayAndHour]: { /* 12-AM */
message: textValueContainer, ['foo']
},
},
}
但可惜它没有添加它覆盖......
任何帮助,将不胜感激。
不要为此使用 object 文字语法。 Object 文字适用于您要创建新的 object 时。 相反,操作 object:
// Checking existence:
if (obj[currentDate] && obj[currentDate][timeOfDayAndHour]) {
console.log('exist');
}
// Checking if message exist:
if (obj[currentDate][timeOfDayAndHour].message) {
console.log('exist');
}
// Adding message array:
obj[currentDate][timeOfDayAndHour].message = [];
// Adding message array with message:
obj[currentDate][timeOfDayAndHour].message = ['foo'];
// Adding message:
obj[currentDate][timeOfDayAndHour].message.push('foo');
现在,使用上面的操作,您可以实现您的逻辑。 我不知道您的确切逻辑是什么,但我们可以演示一种实现。 以下是仅在日期存在时如何添加消息的示例,但如果时间或消息数组存在则无关紧要(它将自动创建它们):
function addMessageToDateAutoCreateEverythingElse (obj, date, time, txt) {
let dateObj = obj[date]
// Checking date exist:
if (dateObj) {
let timeObj = dateObj[time];
// Auto-create time if not exist
if (!timeObj) {
timeObj = {};
dateObj[time] = timeObj;
}
// Auto-create message array if not exist
if (!timeObj.message) {
timeObj.message = [];
}
// Add new message
timeObj.message.push(txt);
}
}
这只是一个逻辑流程。 您可以实现任何您喜欢的逻辑,将任何内容添加到任何 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.