【问题标题】:How can I add a key/value pair to a nested object literal?如何将键/值对添加到嵌套对象文字?
【发布时间】:2017-12-13 10:12:28
【问题描述】:

已解决,此代码所在的函数被调用的频率比预期的要高,因此这些值可能是未定义的,因此向嵌套对象文字添加值将不起作用。我的解决方案是检查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'});

但是在我试图做这样的事情的情况下,这些方法都不起作用,我在这些代码中遇到的错误是 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'});

有没有正确的方法来完成这项工作?

【问题讨论】:

  • 很难理解所有这些代码之间的关系......但我猜你根本没有定义 response.times
  • 你有什么错误吗?
  • Object.assign(response['times]' {executionTime: 'x'});有错误,错字?

标签: javascript object object-literal


【解决方案1】:

确保 responseresponse.times 是对象或空对象,而不是 nullundefined、.. . :

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

【讨论】:

  • 这似乎是一个合乎逻辑的解决方案,但我仍然收到Uncaught TypeError: Cannot set property 'executionTime' of undefined
  • Snippet 工作正常且正确,代码始终正确,我的代码存在缺陷,因为在某些情况下它未定义。
【解决方案2】:

您的代码在这里有效(我删除了 .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);

【讨论】:

  • 这会清除不应该发生的响应(和时间)对象(重新添加注释,因为我删除了错误的注释)。
  • 是的,你是对的。一切都取决于未提供的需要和上下文。很高兴你把它修好了!
猜你喜欢
  • 2019-02-14
  • 2023-01-12
  • 2015-07-27
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多