简体   繁体   English

如何使用JavaScript Lodash将所有对象推入另一个数组

[英]How to push all objects into another array using javascript Lodash

I web API call and in the background, it's running more than one time. 我通过Web API调用,并且在后台运行了不止一次。 So I received the response commentRows as data which I mention. 因此,我收到了响应commentRows作为提及的数据。

I have to map those data into another array. 我必须将这些数据映射到另一个数组中。

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

It generates the array for as, 它为as生成数组,

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

Needed 需要

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

but I don't want the first [] has to be appended Can I use any Lodash for achieving this 但我不希望在第一个[]后面附加我可以使用Lodash来实现这一点

Here is an solution which can handle multiple elements in value array: 这是一个可以处理value数组中多个元素的解决方案:

use _.flatten : 使用_.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

 var arrPush = []; var commentRows = { '@odata.context':'https:indexes', value:[ { "key":"176611", "status":true, "errorMessage":null, "statusCode":200 } ] }; commentRows.value.forEach(x => arrPush.push(x)) console.log(arrPush); 

Use a forEach loop and push them into arrPush 使用forEach循环并将其推入arrPush

像这样推送arrPush.push(commentRows.value [0]);

You can use 您可以使用

arrPush = _.concat(arrPush, commentRows.value[0]).

Here arrayToCopy is the array to which you want to copy the data. 在这里,arrayToCopy是要将数据复制到的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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