I map an Object and run through an array, if they have the same key I create an Object for that user.
What I'm now trying to achieve is, before I push that user Object into an array, I would like to check if that user already exist´s in that array and IF yes, just extend the object by the dates, otherwise push the object into the array.
But my current result is an empty array and I don't know how to overcome this issue. What exactly is not working is mentioned as a comment in the fiddle:
var allUser = [
{ "userLogin": "t.test" },
{ "userLogin": "a.test" },
{ "userLogin": "b.test" }
];
var userFound = ["t.test","a.test"]
var requestByRange = [{
"dateFrom": "2016-09-01",
"dateTo": "2016-09-13",
"userID": "13",
"userLogin": "t.test"
}, {
"dateFrom": "2016-09-09",
"dateTo": "2016-09-16",
"userID": "16",
"userLogin": "t.test"
}, {
"dateFrom": "2016-09-08",
"dateTo": "2016-09-23",
"userID": "16",
"userLogin": "a.test"
}];
var usersToDisplay = [];
if (userFound.length != 0 && requestByRange != undefined) {
allUser.map(function (value, index) {
for (var i = 0; i < userFound.length; i++) {
if (value.userLogin === userFound[i]) {
for(var key in requestByRange){
if(requestByRange.hasOwnProperty(key) && key.indexOf(value.userLogin) === -1){
//console.log("yipia")
//console.log(key)
//console.log(requestByRange[key].dateFrom)
//console.log(requestByRange[key].dateTo)
//console.log(value)
var userToDisplay = {
userLogin: value.userLogin,
dateFrom: [requestByRange[key].dateFrom],
dateTo: [requestByRange[key].dateTo]
}
/*
THE PART BELOW DOES NOT WORK!!!
If userToDisplay.userLogin is already in usersToDisplay
Push the dates in dateFrom and dateTo, otherwise
push the userToDisplay Object into the usersToDisplay array
Current output is an empty array
*/
console.log("--------------------------------------")
for(var usersKey in usersToDisplay){
console.log(usersToDisplay[usersKey])
if(usersToDisplay.hasOwnProperty(usersKey) && usersKey.indexOf(usersToDisplay.userLogin) === -1){
console.log("ja");
console.log(usersToDisplay[usersKey])
usersToDisplay[usersKey].dateFrom.push(userToDisplay.dateFrom)
usersToDisplay[usersKey].dateTo.push(userToDisplay.dateTo)
}else{
console.log("--------------------------------------")
usersToDisplay.push(userToDisplay);
}
}
}
}
}
}
});
}
console.log(usersToDisplay)
The Result should be an array that contains an object where each userLogin exist just once and with all dateFrom & dateToas an array in that object that belongs to this user.
var usersToDisplay = [
{
"dateFrom": ["2016-09-01", "2016-09-09"],
"dateTo": ["2016-09-13, "2016-09-16],
"userID": "16",
"userLogin": "t.test"
}
]