【问题标题】:Adding keypairs to an array of objects in typescript将密钥对添加到打字稿中的对象数组
【发布时间】:2017-03-14 13:37:58
【问题描述】:

我有这个对象数组,但在向打字稿中的对象添加更多密钥对时遇到问题。

例如我有这个数组。

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

我想在这里添加更多内容

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

新值来自另一个数组,我怎样才能(有效地)循环并动态添加更多密钥对?我是打字稿的新手。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您可以使用数组方法检查对象是否包含属性,如果不包含则将属性添加到对象中。..

    检查以下代码sn-p

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

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      您将获得对data 对象的引用:

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

      ...然后循环遍历数组,例如使用无聊的旧 for 循环(但那里有 很多 选项;请参阅 this question's answers 以了解它们是什么) :

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

      ...在循环中,您使用括号表示法(请参阅this question's answers)将属性添加到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;
      });
      

      【讨论】:

        【解决方案3】:

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

        显然,您可以使用for 循环遍历accountsOptions

        您可以从这些 SO 中获得更多想法: Add a Key Value Pair to an array of objects in javascript?How can I add a key/value pair to a JavaScript object?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-24
          • 1970-01-01
          • 1970-01-01
          • 2018-06-10
          • 1970-01-01
          • 2020-08-06
          • 2020-01-27
          • 2023-03-07
          相关资源
          最近更新 更多