簡體   English   中英

將密鑰對添加到打字稿中的對象數組

[英]Adding keypairs to an array of objects in typescript

我有這個對象數組,並且在向打字稿中的對象添加更多密鑰對時遇到問題。

例如我有這個數組。

 accountsOptions:any = [
                          {'data': 
                                    {
                                      'adidas': null, 
                                      'google': null
                                    }
                          }
                        ];

我想在這里添加更多

 accountsOptions:any = [
                              {'data': 
                                        {
                                          'adidas': null, 
                                          'google': null,
                                          'nike': null,
                                          'apple': null
                                        }
                              }
                            ];

新值來自另一個數組,我該如何循環(有效)並動態添加更多密鑰對? 我是打字稿新手。

您可以使用數組方法,並檢查對象是否包含該屬性,如果不包含該屬性,則將該屬性添加到該對象。

檢查以下代碼片段

 "use strict"; var accountsOptions = [ { 'data': { 'adidas': null, 'google': null } } ]; function addProperty(propertyName) { accountsOptions.map(function (account) { if (!account.data.hasOwnProperty(propertyName)) { account.data[propertyName] = null; } }); } addProperty('nike'); console.log(accountsOptions) 

希望能幫助到你

您獲得對data對象的引用:

var data:any = accountsOptions[0].data;

...然后循環遍歷數組,例如,使用無聊的for循環(但那里有很多選項;請參閱此問題的答案以了解它們是什么):

for (var i:number = 0; i < yourArray.length; ++i) {
    // ...
}

...然后在循環中,使用方括號表示法(請參閱此問題的答案 )向data對象添加屬性:

data[yourArray[i]] = null;

例如:

var data:any = accountsOptions[0].data;
for (var i:number = 0; i < yourArray.length; ++i) {
    data[yourArray[i]] = null;
}

但同樣,您有幾個循環選項。 這是另一個:

var data:any = accountsOptions[0].data;
yourArray.forEach((entry:string) => {
    data[entry] = null;
});

嘗試accountsOptions[0].data.nike = null

很明顯,你可以通過循環accountsOptions使用for循環。

您可以從這些SO中獲得更多的想法: 向javascript中的對象數組添加鍵值對? 以及如何將鍵/值對添加到JavaScript對象?

暫無
暫無

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

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