[英]array of objects and adding a function as a property and access other properties using this in typescript
[英]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.