且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用数组中的数据更改对象字段

更新时间:2022-05-25 08:54:14

我不完全理解你的数据结构,但如果我认为:

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


  • IndividualData.account.id 不可靠

  • IndividualData.account.fullName 是reliab le

  • IndividualData.account.positions 是一个数组,每个 IndividualData.account $包含一个元素c $ c>

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

我想出的解决方案是过滤 IndividualData.account 在使用reduce之前具有主要位置的s,并在 fullName 而不是 Id 上执行整个操作:

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
}



编辑



根据您的评论,如果用户在IndividualData中没有主要职位,您必须将他的职位设置为您在IndividualData中为该用户获得的第一个职位。在这种情况下,您可以删除我之前代码段的过滤器部分,并在您的缩减中使用以下方法:

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:


  • 如果当前项目有一个主要位置,将其添加到当前[item.account.fullName]

  • 否则,如果有没有为当前项目的fullName存储任何内容,将其添加到当前[item.account.fullName]

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;
}, {} );