Change Object Fields with Data from Array

前端 未结 1 394
执念已碎
执念已碎 2021-01-26 07:52

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

相关标签:
1条回答
  • 2021-01-26 08:18

    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;
      }, {} );
      
    0 讨论(0)
提交回复
热议问题