gpt4 book ai didi

javascript - 如何将对象数组转换为自定义分组数组

转载 作者:行者123 更新时间:2023-11-30 13:48:46 25 4
gpt4 key购买 nike

我正在尝试将数据对象转换为自定义格式

这是我要转换的数据

[
{ Name: 15, GroupID: 1, Id: 1 },
{ Name: 16, GroupID: 1, Id: 1 },
{ Name: 17, GroupID: 2, Id: 2 },
{ Name: 18, GroupID: 2, Id: 2 },
{ Name: 15, GroupID: 3, Id: 3 },
{ Name: 16, GroupID: 3, Id: 3 },
{ Name: 17, GroupID: 4, Id: 4 },
{ Name: 18, GroupID: 4, Id: 4 }
];

这就是我想要的

  { GroupID: 1 },

{ Name: 15, Id: 1 },
{ Name: 16, Id: 1 },

{ GroupID: 2 },

{ Name: 17, Id: 2 },
{ Name: 18, Id: 2 },

{ GroupID: 3 },

{ Name: 15, Id: 3 },
{ Name: 16, Id: 3 },

{ GroupID: 4 },

{ Name: 17, Id: 4 },
{ Name: 18, Id: 4 }

这是我目前尝试的方法

var data = [
{ Name: 15, GroupID: 1, Id: 1 },
{ Name: 16, GroupID: 1, Id: 1 },
{ Name: 17, GroupID: 2, Id: 2 },
{ Name: 18, GroupID: 2, Id: 2 },
{ Name: 15, GroupID: 3, Id: 3 },
{ Name: 16, GroupID: 3, Id: 3 },
{ Name: 17, GroupID: 4, Id: 4 },
{ Name: 18, GroupID: 4, Id: 4 }
];

var previousGroupId;
var newObject = new Object();
for (index in data) {
var groupId = data[index].GroupID;
if (groupId != previousGroupId) {
var newGroup = "GroupId" + groupId;
newObject[newGroup] = new Array();
for (index in data) {
if (data[index].GroupID == groupId) {
var customObject = {
"GroupID": groupId,
"Name": data[index].Name,
"Id": data[index].Id
};
newObject[newGroup].push(customObject);
}
}
}
previousGroupId = groupId;
}

console.log(newObject);

即使我试图提及这个 Javascript group objects by property

任何建议都会有所帮助。

最佳答案

假设一个对象数组作为结果集,您可以采用带有数组的哈希表并将平面数组作为结果集。

var data = [{ Name: 15, GroupID: 1, Id: 1 }, { Name: 16, GroupID: 1, Id: 1 }, { Name: 17, GroupID: 2, Id: 2 }, { Name: 18, GroupID: 2, Id: 2 }, { Name: 15, GroupID: 3, Id: 3 }, { Name: 16, GroupID: 3, Id: 3 }, { Name: 17, GroupID: 4, Id: 4 }, { Name: 18, GroupID: 4, Id: 4 }],
result = Object
.values(data.reduce((r, { Name, GroupID, Id }) => {
r[GroupID] = r[GroupID] || [{ GroupID }];
r[GroupID].push({ Name, Id });
return r;
}, {}))
.flat();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何将对象数组转换为自定义分组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58725277/

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