javascript - 转换对象数组和连接对象值
问题描述
我有一个需要转换为新对象数组的对象数组。有没有一种方法可以在不手动定义"texas"
或"california"
定义新的对象数组时完成?
这是我的原始数据:
const data = [
{
year: "2005",
texas: 6.984323232343243
},
{
year: "2006",
texas: 8.507629970573532
},
{
year: "2005",
california: 8.422823214889691
},
{
year: "2006",
california: 9.456857576876532
}
];
我需要它看起来像这样:
const newData = [
{
year: 2005,
texas: 6.984323232343243,
california: 8.422823214889691
},
{
year: 2006,
texas: 8.507629970573532,
california: 9.456857576876532
}
];
我试图对这些对象进行分组,然后取消分组,但我只能进行分组并且似乎无法弄清楚如何按照我需要的方式取消分组。有没有办法在不先分组的情况下做到这一点?
const data = [
{
year: "2005",
texas: 6.984323232343243
},
{
year: "2006",
texas: 8.507629970573532
},
{
year: "2005",
california: 8.422823214889691
},
{
year: "2006",
california: 9.456857576876532
}
];
const groupByReduce = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
)
return result
}, {});
};
const newData = groupByReduce(data, "year");
console.log(newData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
解决方案
你可以reduce
这样使用——
const data = [
{year: "2005", texas: 6.984323232343243},
{year: "2006", texas: 8.507629970573532},
{year: "2005", california: 8.422823214889691},
{year: "2006", california: 9.456857576876532}
];
let res = data.reduce((a, c) => ({...a, [c.year]: {...a[c.year], ...c}}), {});
res = Object.values(res);
console.log(res);
.as-console-wrapper {min-height: 100%!important; top: 0}
推荐阅读
- javascript - 函数中的 React useState 方法无法按预期工作
- python - TF Keras v 1.14+:“模块”的子类模型或子类层
- python - Pandas - 基于一周的最后一个工作日的条件列创建
- sql - sql、oracle中的row_number计算
- java - 为什么有时我们应该将 jvm 参数 -Xms 和 -Xmx 设置为相同的值?这有什么好处?
- ansible - 如何评估 Ansible 模板?它们被“递归评估”是什么意思?
- php - 从数组创建有效负载
- android - 深度链接在 Android pie 中不起作用?
- mysql - mysql 在添加新索引时有时会删除旧索引?
- c# - “System.InvalidOperationException:'实体类型用户不是当前上下文模型的一部分。'”