LoDash Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.0/lodash.min.js"></script>
JavaScript
// loaded from API Request into array
var OnlineList = [];
// Sorted and ordered for display
var OnlineUsers = [];
OnlineList = [
{
"Role": "Adjuster",
"AccountId": "4",
"UserId": "1e72d58e",
"DisplayName": "Big Bob",
},
{
"Role": "Adviser",
"AccountId": "5",
"UserId": "a0daba73",
"DisplayName": "Sassy Sally",
}
];
// GroupBy function: https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects/43215522
let groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
// Simulates a get by Id API service
let accountService = (id) => {
if (id == 4) {
return "ClaimsCo."
}
else {
return "Dealership"
}
}
// pass in AccountId
let getAccountName = function(int) {
var accountName = "";
//get AccountName from Id
accountName = accountService(int);
for(var x=0; x < OnlineList.length; x++){
// check for AccountId
if(OnlineList[x].hasOwnProperty('AccountId')){
// Set AccountId value to AccountName
OnlineList[x].AccountId = accountName;
// Group results and set to OnlineUsers array
OnlineUsers = groupBy(OnlineList, 'AccountId');
break;
}
}
};
// Go into first element of array and get AccountId value
var id = _.get(OnlineList[0], "AccountId");
// Convert value to int
var int = parseInt(id,10);
// Pass into function that gets AccountName from AccountId and replaces AccountId in that element of OnlineList array
getAccountName(int);
//result
console.log(OnlineUsers);