【问题标题】:Javascript object in array数组中的 Javascript 对象
【发布时间】:2016-02-16 11:47:08
【问题描述】:

假设我有一个像

这样的对象
> var products = {a:"b", c:"d", e:"f" ... it goes like this}

我想把这个对象放在这样的数组中

> var arrList = [[a,b],[c,d],[e,f]]

但是如果你们能帮助我,我会做得很好,谢谢你们

【问题讨论】:

    标签: javascript arrays object


    【解决方案1】:

    只需循环并将其添加到数组中

    var result = []
    for (var key in products) { result.push([key,products[key]]) }
    

    【讨论】:

      【解决方案2】:

      一种可能的方法:

      var arrList = Object.keys(products).map(function(key) {
        return [key, products[key]];
      });
      

      但请注意,properties order in objects are not guaranteed in JavaScript

      【讨论】:

      【解决方案3】:

      你可以这样继续:

      var products = {a:"b", c:"d", e:"f"};
      
      var arrList = [];
      for(var key in products) { // iterates over products key (e.g: a,c,e)
         arrList.push([key, products[key]]);
      };
      

      【讨论】:

        【解决方案4】:

        使用for-in循环遍历对象

        for(对象中的变量)=> 变量是一个属性名

        试试这个:

        var products = {
          a: "b",
          c: "d",
          e: "f"
        };
        var arr = [];
        for (i in products) {
          arr.push([i, products[i]]);
        }
        snippet.log(JSON.stringify(arr));
        <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

        【讨论】:

          【解决方案5】:

          你可以这样做

          products = {a:"b",c:"d",e:"f"};
          arrList = [];
          for(i in products){
              arrList.push([i,products[i]]);
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-09-26
            • 2015-08-07
            • 1970-01-01
            • 2020-07-25
            • 2011-09-29
            相关资源
            最近更新 更多