我正在尝试将2个对象数组合并为一个对象数组,同时保持save()
在合并数组中的顺序。
在arr1
中存在arr1
中存在的internalName
键。 arr2
中的type
键代表arr1
中键的值-例如,arr2
中的avg
类型应映射到arr1
具有相同average
的{{1}}的密钥。
arr2
预期结果:
internalName
我已经使用带有嵌套const arr1 = [
{internalName: "14_17_years_old", type: "avg"},
{internalName: "14_17_years_old", type: "sum"},
{internalName: "18_24_years_old", type: "avg"},
{internalName: "25_34_years_old", type: "sum"},
{internalName: "35_44_years_old", type: "avg"},
{internalName: "35_44_years_old", type: "sum"},
{internalName: "activity_attendance", type: "sum"},
];
const arr2 = [
{average: 83, count: 7, internalName: "14_17_years_old", name: "14-17 Years Old", sum: 578},
{average: 168, count: 11, internalName: "18_24_years_old", name: "18-24 Years Old", sum: 1850},
{average: 193, count: 11, internalName: "25_34_years_old", name: "25-34 Years Old", sum: 2126},
{average: 237, count: 10, internalName: "35_44_years_old", name: "35-44 Years Old", sum: 2370},
{average: 828, count: 28, internalName: "activity_attendance", name: "Activity Attendance", sum: 23190}
];
的{{1}}开始了这条路线,但没有返回任何内容。
const expected = [
{internalName: "14_17_years_old", name: "14-17 Years Old", type: "avg", value: 83},
{internalName: "14_17_years_old", name: "14-17 Years Old", type: "sum", value: 578},
{internalName: "18_24_years_old", name: "18-24 Years Old", type: "avg", value: 168},
{internalName: "25_34_years_old", name: "25-34 Years Old", type: "sum", value: 2126},
{internalName: "35_44_years_old", name: "35-44 Years Old", type: "avg", value: 237},
{internalName: "35_44_years_old", name: "35-44 Years Old", type: "sum", value: 2370},
{internalName: "activity_attendance", name: "Activity Attendance", type: "sum", value: 23190},
];
实际上有一个两部分的问题-如何在没有太多代码的情况下完成此任务?
答案 0 :(得分:1)
您可以使用arr2
进行查找,以允许恒定时间检索对象。然后,您可以map
遍历arr1
中的项目并构建新结果数组的对象:
const arr1 = [{internalName: "14_17_years_old", type: "avg"},{internalName: "14_17_years_old", type: "sum"},{internalName: "18_24_years_old", type: "avg"},{internalName: "25_34_years_old", type: "sum"},{internalName: "35_44_years_old", type: "avg"},{internalName: "35_44_years_old", type: "sum"},{internalName: "activity_attendance", type: "sum"},];
const arr2 = [{average: 83, count: 7, internalName: "14_17_years_old", name: "14-17 Years Old", sum: 578},{average: 168, count: 11, internalName: "18_24_years_old", name: "18-24 Years Old", sum: 1850},{average: 193, count: 11, internalName: "25_34_years_old", name: "25-34 Years Old", sum: 2126},{average: 237, count: 10, internalName: "35_44_years_old", name: "35-44 Years Old", sum: 2370},{average: 828, count: 28, internalName: "activity_attendance", name: "Activity Attendance", sum: 23190}];
let lookup = arr2.reduce((map, {internalName, average:avg, sum, name }) => map.set(internalName, {avg, sum, name}), new Map)
let res = arr1.map(({internalName, type}) => ({
internalName,
type,
value: lookup.get(internalName)[type],
name: lookup.get(internalName)['name']
}))
console.log(res)