2016-06-07 277 views
0

该函数将返回一个包含商店细节和图像的数组。在nodejs中合并两个数组

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

我需要包含店铺信息和图像转换成单个array.That阵列合并与相应的图像店铺信息。

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

回答

1

你可以通过平坦化阵列降低: [[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); 
     }); 
    }); 

    } 
+0

你写的代码完美无缺。但这里的问题是:{{shopId:3,shopName:'1',地址:'abc',contactNumber:1234}, {imageId:1,shopId:3,imageUrl:'aaa'}, {imageId: 2,shopId:3,imageUrl:'bbb'}] {{shopId:4,shopName:'2',地址:'bbb',contactNumber:1234}, {imageId:3,shopId:4,imageUrl:' ccc'}, {imageId:4,shopId:4,imageUrl:'ddd'}]从这个数组中如何检查shopId = 3的数据。 –

+0

当我给结果[0]它提取了两个商店的细节。当我给结果[1]它获取图像id(1,3)。 –

+0

http://stackoverflow.com/questions/37695717/json-array-is-not-getting-in-expected-format:请检查这个问题。 –