midhun k
midhun k

Reputation: 1068

merging two arrays in nodejs

This function will returns an array containing shop details and images.

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

         });
     });

    }

The output for above code is:: https://i.sstatic.net/laxf8.png

I need to merge the array containing shop information and images into single array.That is shop information with corresponding images.

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

Upvotes: 0

Views: 956

Answers (1)

Federico Ginosa
Federico Ginosa

Reputation: 316

You could flatten the array using reduce: [[1],[2]] --> [1,2]

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

In your case:

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

    }

Upvotes: 1

Related Questions