首页 > 解决方案 > 如何使用 javascript Lodash 将所有对象推入另一个数组

问题描述

我调用 Web API 并在后台运行不止一次。所以我收到了回复commentRows作为我提到的数据。

我必须将这些数据映射到另一个数组中。

var arrPush =[ ]; 
var commentRows ={  
   '@odata.context':'https:indexes',
   value:[  
      {  
         "key":"176611",
         "status":true,
         "errorMessage":null,
         "statusCode":200
      },
      {  
         "key":"176100",
         "status":true,
         "errorMessage":null,
         "statusCode":200
      }
   ]
}; 

arrPush.push(commentRows.value);

它为 as 生成数组,

[  
   [  
      {  
         "key":"176611",
         "status":true,
         "errorMessage":null,
         "statusCode":200
      },
      {  
         "key":"176100",
         "status":true,
         "errorMessage":null,
         "statusCode":200
      }
   ]
]

需要

   [  
      {  
         "key":"176611",
         "status":true,
         "errorMessage":null,
         "statusCode":200
      },
      {  
         "key":"176100",
         "status":true,
         "errorMessage":null,
         "statusCode":200
      }
   ]

但我不希望必须附加第一个 [] 我可以使用任何Lodash来实现这一点 吗

标签: javascriptlodash

解决方案


这是一个可以处理数组中多个元素的解决方案:value

使用_.flatten

var arrPush = [];
var commentRows = {  
       '@odata.context':'https:indexes',
       value:[  
          {  
             "key":"176611",
             "status":true,
             "errorMessage":null,
             "statusCode":200
          }
       ]
    };

arrPush.push(commentRows.value);
arrPush = _.flatten(arrPush);  // here you get it

推荐阅读