For each user in my array I want to take their positionTitle if the \'isPrimary\' is set to true and use this positionTitle to replace all positionTitle\'s of the same user in m
I don't fully understand your data structure, but if I assume that :
IndividualData.account.id
is not reliableIndividualData.account.fullName
is reliableIndividualData.account.positions
is an array that contains one element per IndividualData.account
The solution I came up with is to filter the IndividualData.account
s that has a primary position before using your reduce, and do the whole thing on fullName
instead of Id
:
const accountIdToPositionDict = IndividualData
.filter(item => item.positions.find(p => p.isPrimary))
.reduce( (current, item) => {
current[item.account.fullName] = (item.positions.find( position => position.isPrimary ) || {} ).positionTitle;
return current;
}, {} );
const updatedGraphTable = {
//Long stuff to get to the relevant path...
accountIdToPositionDict[member.account.fullName] || member.position.positionTitle
}
According to your comment, if a user has no primary position in IndividualData, you have to set his position to the first position you get for this user in IndividualData. In that case, you can drop the filter part of my previous snippet and go for the following approach in your reduce:
current[item.account.fullName]
keyElse, if there is nothing stored for the current item's fullName, add it to the current[item.account.fullName]
key
const accountIdToPositionDict = IndividualData
.reduce((current, item) => {
const primaryPosition = item.positions.find(p => p.isPrimary);
if(!current[item.account.fullName] || primaryPosition)
current[item.account.fullName] =
(primaryPosition && primaryPosition.title) ||
item.positions[0].positionTitle;
return current;
}, {} );