Skip to content Skip to sidebar Skip to footer

Change Object Fields With Data From Array

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 my obje

Solution 1:

I don't fully understand your data structure, but if I assume that :

  • IndividualData.account.id is not reliable
  • IndividualData.account.fullName is reliable
  • IndividualData.account.positions is an array that contains one element per IndividualData.account

The solution I came up with is to filter the IndividualData.accounts 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
}

Edit

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:

  • If the current item has a primary position, add it to the current[item.account.fullName] key
  • Else, 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;
    }, {} );
    

Post a Comment for "Change Object Fields With Data From Array"