ES6:只有当 属性 存在时,如何才能有条件地将 属性 (它本身是一个对象)添加到对象

ES6: How can you add a property (which itself is an object) to an object conditionally only if that property exists

我正在关注这个伟大的 tutorial 以根据条件向对象添加 属性(或不添加)。

例如:

{  id: 'some-id',  ...(true && { optionalField: 'something'})}

但在我的例子中,我有一个看起来像这样的对象:

我想做的是如果12-AM 属性存在,不要覆盖它,添加到 属性这是一个名为 message 的键,它是一个数组

如果它不添加新的时间密钥,即 1230-AMApril-9-2020

这是我现在拥有的:

{
  ...dayInfoInChild,
  [currentDate]: { /* April-9-2020 */
    [timeOfDayAndHour]: { /* 12-AM */
      message: textValueContainer, ['foo']
    },
  },
}

但可惜它没有添加它覆盖...

如有任何帮助,我们将不胜感激。

不要为此使用对象字面量语法。对象字面量用于当你想创建一个新对象时。相反,操纵对象:

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

这只是一个逻辑流程。您可以实现任何您喜欢的逻辑,向任何对象添加任何内容。