简体   繁体   中英

Adding keypairs to an array of objects in typescript

I have this Array of objects, and I am having problems adding more key-pairs to the objects in typescript.

For Example I have this Array.

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

And I want to add more here

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

the new values are coming from another array, how can I loop(efficiently) this and dynamically add more key-pairs? I am new to typescript.

You can make use of array methods and check if the object contains the property, if it does not contain add the property to the object..

check the following code snippet

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

Hope it helps

You get a reference to the data object:

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

...and then you loop through your array, for instance with a boring old for loop (but you have lots of options there; see this question's answers to know what they are):

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

...and in the loop, you use brackets notation (see this question's answers ) to add properties to the data object:

data[yourArray[i]] = null;

Eg:

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

But again, you have several options for the loop. Here's another one:

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

Try accountsOptions[0].data.nike = null .

Obviously you can loop through accountsOptions using a for loop.

You can have more idea from these SO: Add a Key Value Pair to an array of objects in javascript? and How can I add a key/value pair to a JavaScript object?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM