簡體   English   中英

如何將鍵/值對添加到嵌套對象文字中?

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

已解決,此代碼所在的函數被調用的次數比預期的要多,因此,值可能是不確定的,因此無法將值添加到嵌套對象文字中。 我的解決方案是檢查是否response.times is definedresponse.times is defined ,僅在這種情況下才添加值。

我在嘗試將鍵值對添加到javascript對象中的對象時遇到了一些麻煩。

我主要在以下主題中研究解決方案,因為找不到與我的問題更接近的東西。

如何將鍵/值對添加到JavaScript對象?

我處於一種情況,在這種情況下,我會得到一堆返回的對象或執行時間,這些時間用來確定我的應用程序變慢的地方(服務器,數據庫,查詢等)。 但是,所有這些時間都存在於從服務器傳遞的響應對象中。

為了更改此設置,我在所有這些時間中都在響應中創建了一個特定的對象。 問題是我仍將所有這些時間戳添加到主響應對象中,然后再將其更改為該對象。

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

有沒有正確的方法來完成這項工作?

確保responseresponse.times是對象或空對象,而不是nullundefined ,...:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM