-1

I'm doing an Api call to receive some data about the users i'm following. And for the moment i receive something like that [[{obj1},{obj2}],[{obj3}]] and I want something like this [{obj1},{obj2},{obj3}]. Because one user can have more than one object.

 getDashboard = function (req, res) {
  User.findById(req.params.id, function (err, user) {
        if (!user) {
            res.send(404, 'User not found');
        }
        else {
            var a = user.following;
            var promises = a.map(function(current_value) {
            return new Promise(function(resolve, reject) {
            Receta.find({"user_id":current_value._id}, function (err, recetas) {
            if(!err) {              
                    resolve(recetas);
            } else {
                    reject(err);
                    }
            });
            });
            });

            Promise.all(promises).then(function(allData) {
                var proms = allData.map(function(value){
                    return value 
                    });
                res.send(proms);
            }).catch(function(error) {
                res.send(error);
            });
        }
  });
};
david raja
  • 87
  • 11

2 Answers2

2

You could use ES6 Spread

 var data = [["one", "two"],["three"],["four","five"]];
 result = [].concat(...data);
 console.log(result);
 

Alternative in ES5 you could use reduce :

var data = [["one", "two"],["three"],["four","five"]];
var result = data.reduce(function(prev,curv){
    return prev.concat(curv)
}, []);

console.log(result);
Sing
  • 3,942
  • 3
  • 29
  • 40
0

EDIT I'm not quite sure this is what the question was asking, but this was my interpretation

So you want to flatten out an array? Let's first build a function that takes a nested array and flattens it out a single level, like so:

function flatten(arr){
    var result = [];
    arr.forEach(element => (
        result = result.concat(element);
    ));
    return result;
}

Now, what if we have a 3D array, like [[["hi"]]]. Then, we need to flatten it multiple times. In fact, we can do this recursively.

Each time, we can check if it's an array using Array.isArray(), and if it is, flatten it before appending. We can program this recursively.

function flatten(arr){
    var result = [];
    arr.forEach(element => (
        result = result.concat(Array.isArray(element) ? flatten(element) : element)
    ));
    return result;
}

and that is our final answer. With that second function, we can see that flatten(["hi", ["there"]]) works.

Max
  • 1,325
  • 9
  • 20