在nodejs中合并两个数组

时间:2016-06-07 12:52:48

标签: arrays node.js express

此函数将返回包含商店详细信息和图像的数组。

function listshops(callback)
    {   
     var array=[3,4];
      async.each(array,function(dat,callback){

         async.parallel([

             function(callback){
                c    function listshops(callback)
    {   
     var array=[3,4];/*shopId*/
      async.each(array,function(dat,callback){

         async.parallel([

             function(callback){
                client.connection.query('select * from shop where shopId=?',dat,function(err,data1){
                callback(null,data1);

               });
            },       

             function (callback) {
                client.connection.query('select * from image where shopId=?',dat,function(err,data2){
                callback(null,data2);

               });
            }
         ],
         function(err,data)
         {
         console.log(data);

         });
     });

    }

上述代码的输出为:: http://i.stack.imgur.com/laxf8.png

我需要将包含商店信息和图像的数组合并为单个数组。这是具有相应图像的商店信息。

[
    { shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 },
    { imageId: 1, shopId: 3, imageUrl: 'aaa' },
    { imageId: 2, shopId: 3, imageUrl: 'bbb' } 
]

1 个答案:

答案 0 :(得分:1)

您可以使用reduce来展平数组: [[1],[2]] - > [1,2]

var array = [[1,2],[3]];
array.reduce(function(prev, curr) {
  return prev.concat(curr);
});

在你的情况下:

  function listshops(callback)
    {   
     var array=[3,4];/*shopId*/
      async.each(array,function(dat,callback){

         async.parallel([

             function(callback){
                client.connection.query('select * from shop where shopId=?',dat,function(err,data1){
                callback(null,data1);

               });
            },       

             function (callback) {
                client.connection.query('select * from image where shopId=?',dat,function(err,data2){
                callback(null,data2);

               });
            }
         ],
         function(err,data)
         {
            var result = data.reduce(function(prev, curr) {
              return prev.concat(curr);
            });
            console.log(result);
         });
     });

    }