如何将 key/value 对添加到嵌套对象文字?

How can I add a key/value pair to a nested object literal?

已解决,此代码所在的函数的调用频率高于预期,因此值可能未定义,因此向嵌套对象文字添加值将不起作用。我的解决方案是检查 response.times is defined 是否仅在这种情况下添加值。

我目前在尝试向 javascript 对象中的对象添加键值对时遇到了一些麻烦。

我主要是看下面题目的解法,因为没找到更接近我问题的。

How can I add a key/value pair to a JavaScript object?

我遇到这样一种情况,我得到一个返回的对象,其中包含一堆或执行时间,我用它来确定我的应用程序在哪里变慢(服务器、数据库、查询等)。然而,所有这些时间都存在于从服务器传递的响应对象中。

为了改变这一点,我在所有这些时间的响应中创建了一个特定对象。问题是在我将它们更改为这个对象之前,我仍然将所有这些时间戳添加到主响应对象。

response.times = {
  'executionTime': response.executionTime,
  'processingTime': response.processingTime,
}

我希望能够在知道所有这些时间戳后立即将它们添加到该对象中。

可以通过多种方式将值添加到响应对象:

response.executionTime = 'x';
response['executionTime'] = 'x';
Object.assign(response, {executionTime: 'x'});
response.push({executionTime: 'x'});

但是这些方法中的 none 在我尝试做这样的事情的情况下有效,我在这些代码中遇到的错误是 Cannot read property ... of undefined 。在所有情况下,即使设置了值,时间似乎也未定义。

response.times.executionTime = 'x';
response.times['executionTime'] = 'x';
Object.assign(response.times, {executionTime: 'x'});
Object.assign(response['times]', {executionTime: 'x'});
response.times.push({executionTime: 'x'});
response['times'].push({executionTime: 'x'});

是否有正确的方法来完成此操作?

确保responseresponse.times是对象或空对象而不是null, 未定义, ...:[=​​11=]

  var response;
  response = response || {};
  response.times = response.times || {};
  response.times.executionTime = 'x';
  console.log(response);

这里您的代码有效(我删除了 .push() 代码,因为它们用于数组)。您只需要在添加属性之前定义 response 对象和 response.times 对象。

response = {
  times: {}
};
response.times.executionTime1 = 'x';
response.times['executionTime2'] = 'x';
Object.assign(response.times, {
  executionTime3: 'x'
});
Object.assign(response['times'], {
  executionTime4: 'x'
});

console.log(response);