gpt4 book ai didi

javascript - 如何在 java 脚本对象 ES5 中分组和合并

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:54:02 28 4
gpt4 key购买 nike

我有一个这样的对象

{
"User 1":[
{"count":"1","stage":"A","jCount":"10","name":"User 1","stageId":"A1"},
{"count":"8","stage":"B","jCount":"10","name":"User 1","stageId":"B1"},
],

"User 2":[
{"count":"7","stage":"C","jCount":"8","name":"User 2","stageId":"C1"},
{"count":"8","stage":"B","jCount":"8","name":"User 2","stageId":"B1"},
{"count":"9","stage":"A","jCount":"8","name":"User 2","stageId":"A1"},
{"count":"8","stage":"D","jCount":"8","name":"User 2","stageId":"D1"},
],

"User 3":[
{"count":"6","stage":"D","jCount":"6","name":"User 3","stageId":"D1"},
{"count":"8","stage":"B","jCount":"6","name":"User 3","stageId":"B1"},
{"count":"1","stage":"A","jCount":"6","name":"User 3","stageId":"A1"},
],
/* Many more users */
}

我正在尝试以这种格式更改我的对象

[
{
"name":"User 1",
"jCount":10,
"stageIdCountA1":1,
"stageIdCountB1":8,
"stageIdCountC1":0,
"stageIdCountD1":0,
},{
"name":"User 2",
"jCount":8,
"stageIdCountA1":9,
"stageIdCountB1":8,
"stageIdCountC1":7,
"stageIdCountD1":8,
},{
"name":"User 3",
"jCount":6,
"stageIdCountA1":1,
"stageIdCountB1":8,
"stageIdCountC1":0,
"stageIdCountD1":6,
},
/* Many more users */
]

最多只有 4 个阶段 A1,B1,C1,D1jCount 在子对象的用户数组中很常见

如果没有没有阶段,它应该打印0

我尝试在 angularjs View 中进行操作,但它变得很困难。

最佳答案

您可以使用 map 将每个用户对象映射到数组中的一个项目,并在 map 函数内使用 reduce 将阶段数组变成单个对象:

const input={"User 1":[{"count":"1","stage":"A","jCount":"10","name":"User 1","stageId":"A1"},{"count":"8","stage":"B","jCount":"10","name":"User 1","stageId":"B1"},],"User 2":[{"count":"7","stage":"C","jCount":"8","name":"User 2","stageId":"C1"},{"count":"8","stage":"B","jCount":"8","name":"User 2","stageId":"B1"},{"count":"9","stage":"A","jCount":"8","name":"User 2","stageId":"A1"},{"count":"8","stage":"D","jCount":"8","name":"User 2","stageId":"D1"},],"User 3":[{"count":"6","stage":"D","jCount":"6","name":"User 3","stageId":"D1"},{"count":"8","stage":"B","jCount":"6","name":"User 3","stageId":"B1"},{"count":"1","stage":"A","jCount":"6","name":"User 3","stageId":"A1"},],};

const stages = ['A', 'B', 'C', 'D'];
const output = Object.entries(input).map(([name, arr]) => {
const { jCount } = arr[0];
const stageCounts = stages.reduce((a, stageName) => {
const propName = 'stageIdCount' + stageName;
const foundStage = arr.find(({ stage }) => stageName === stage);
const count = foundStage ? foundStage.count : 0;
a[propName] = count;
return a;
}, {});
return { name, jCount, ...stageCounts };
});
console.log(output);

如果你不能使用扩展语法(你应该 - 如果可能的话将 Babel 集成到你的构建过程中),然后替换

return { name, jCount, ...stageCounts };

return Object.assign({ name, jCount }, stageCounts);

关于javascript - 如何在 java 脚本对象 ES5 中分组和合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50652548/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com