Node.js - 如何根据条件合并数组内的对象?

分享于2022年07月17日 arrays hash javascript node.js object 问答
【问题标题】:Node.js - 如何根据条件合并数组内的对象?(Node.js - How to merge objects inside an array based on condition?)
【发布时间】:2022-01-26 21:47:20
【问题描述】:

在 Node.js 中,我有 3 组数据,例如

[
    {
        "userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
        "dailyData":159392.235451,
        "dailyDataInUSC":255.284807
    }
] 

[
    {
        "userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
        "monthlyData":159392.235451,
        "monthlyDataInUSC":255.284807
    }, 
    {
        "userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
        "monthlyData":349392.455451,
        "monthlyDataInUSC":655.234807
    }
] 

[
    {
        "userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
        "threeMonthsData":159392.235451,
        "threeMonthsDataInUSC":255.284807
    }, 
    {
        "userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
        "threeMonthsData":349392.455451,
        "threeMonthsDataInUSC":655.234807
    }, 
    {
        "userId":"34sdf34-67j4-54nd-6763-d2ec81e8aaf3",
        "threeMonthsData":6789392.455451,
        "threeMonthsDataInUSC":905.655807
    }
] 

如何根据数组中的 userId (filter) 将其组合到一个对象中。

例如,输出应该是这样的

[
    {
        "userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
        "dailyData":159392.235451,
        "dailyDataInUSC":255.284807,
        "monthlyData":159392.235451,
        "monthlyDataInUSC":255.284807,
        "threeMonthsData":159392.235451,
        "threeMonthsDataInUSC":255.284807
    }
]

请帮助我实现这一目标。


【解决方案1】:

spread reduce findIndex 的组合可用于解决问题。

  • 使用 spread 运算符将原始数组组合成一个数组。
  • 使用 reduce 按键对元素进行分组(在本例中为 userId

类似这样的:

const dailyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","dailyData":159392.235451,"dailyDataInUSC":255.284807}];
const monthlyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","monthlyData":159392.235451,"monthlyDataInUSC":255.284807}, {"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3","monthlyData":349392.455451,"monthlyDataInUSC":655.234807}]
const triMonthlyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","threeMonthsData":159392.235451,"threeMonthsDataInUSC":255.284807}, {"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3","threeMonthsData":349392.455451,"threeMonthsDataInUSC":655.234807}, {"userId":"34sdf34-67j4-54nd-6763-d2ec81e8aaf3","threeMonthsData":6789392.455451,"threeMonthsDataInUSC":905.655807}]


const combinedData = [...dailyData, ...monthlyData, ...triMonthlyData].reduce((mergedResult, curElement) => {
  let matchingElementIdx = mergedResult.findIndex(ele => ele.userId === curElement.userId);

  if (matchingElementIdx !== -1) {
    mergedResult[matchingElementIdx] = {...mergedResult[matchingElementIdx], ...curElement};
  } else {
    mergedResult = [...mergedResult, curElement];
  }
  return mergedResult;
}, []);

console.log(combinedData);