I have an array of models where I have the type and key.
models = [{type: 'user', key: getKey('user')},
//.
//.Many more model objects here
//.
{type: 'employee', key: getKey('employee')}];
Here I'm mapping each of the model to my search function which gets data for each model:
async.map(models, search, function (err, results) {
if (err) {
res.json(400, err);
} else {
// Here results is an array of arrays of different results for different models and I dont know how to check
// how to find different models with the same key and union their results if they have the same key value...
var mergedResult = [];
mergedResult = mergedResult.concat.apply(mergedResult, results);
res.json(200, mergedResult);
}
});
And Here is my search function which returns for passed model name:
function search(model, callback) {
getData(model.type, callback);
}
So now I'm getting the result for each model (user, customer,... and employee), but now I want to check if any of these models have the same key which I get by getKey(modelName) function; in our example lets say the key for user and employee is the same and it is "name" field, so in this case I want to union (like the union in sql) the results of employee and user: lets say for "user" we get:
Results for user model:
[
{
name : "Mike",
age: 33
eyeColor: "brown"
},
{
name : "David",
age: 35
}
]
and for employee we get :
Results for Employee model:
[
{
name : "Mike",
age: 33,
heigh: 178,
eyeColor: "black"
},
{
name : "Nanacy",
age: 39
}
]
The desired results:
[
{
name : "Mike",
age: 33
eyeColor: "brown",
heigh: 178
},
{
name : "David",
age: 35
},
{
name : "Nanacy",
age: 39
}
]
In my algorithm I'm just simply returning:
What I'm returning:
[
{
name : "Mike",
age: 33
eyeColor: "brown"
},
{
name : "David",
age: 35
},
{
name : "Mike",
age: 33,
heigh: 178,
eyeColor: "black"
},
{
name : "Nanacy",
age: 39
}
]
Please let me know if I you need more calrification! Thanks
async? Could you have solved the problem if the functions were synchronous? If so, please show us that (pseudo-)code, it might be easier to understand than your text.Object.keys/[].keys()insteadasync.mapretains the order of the items.results[0]will be the result ofgetData(models[0].type)and so on. With that information, you can simply loop the models to determine in what order which result sets should be merged on what key, and then just reference each result set by its index. Your "union" algorithm is a bit underspecified though, so you'll have to figure that out yourself (e.g. how it would deal with the data if Mike's age would be different in the two results).