简体   繁体   中英

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. So I received the response commentRows as data which I mention.

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,

[  
   [  
      {  
         "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

Here is an solution which can handle multiple elements in value array:

use _.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

像这样推送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.

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