【发布时间】:2018-07-24 18:33:26
【问题描述】:
以这个极其简化的对象数组为例:
[
{
createID: '1'
// Many other properties...
},
{
createID: '1'
// Many other properties...
},
{
createID: '1'
// Many other properties...
},
{
createID: '37'
// Many other properties...
},
{
createID: '37'
// Many other properties...
},
{
createID: '2'
// Many other properties...
},
{
createID: '2'
// Many other properties...
},
{
createID: '14'
// Many other properties...
},
];
给定这个数组,然后我使用对象createID 属性创建一个包含对象[[{..},{..}], [{..}], ..n] 的数组数组。我正在使用的当前前端框架(Angular v6)需要这种最终格式。
为了完成这项任务,我使用以下代码,其中tempArr 是一个类似于上面提供的示例数组的数组。
let currentGroup: string = tempArr[0].createID;
let tempGrouped: any[] = [];
let childGroup: any[] = [];
tempArr.forEach(item => {
if (item.createID !== currentGroup) {
tempGrouped.push(childGroup);
childGroup = [];
currentGroup = item.createID;
}
childGroup.push(item);
});
tempGrouped.push(childGroup);
此代码运行良好。但是,我不禁相信必须有一种更高效、更优雅的方法,将对象数组转换为包含对象的数组。
更新
请务必注意,createID 的 只是表示应将哪些对象组合在一起的 id。 因此,它们不需要按createID 进行数字排序。此外,正如您在提供的给定示例数组中所见,这些对象确实来自与其兄弟对象(相同的createID)“分组”的服务器。
【问题讨论】:
-
如果您可以为 stackblitz 提供一个工作示例,我们将更容易提供工作替代方案。 :-)
-
更优雅?使用
for … of而不是.forEach。更高效?不,你所拥有的是最佳的。 -
具有相同 ID 的对象是否总是彼此相邻?
-
@MarkMeyer,是的,他们会的 - 在问题中查看我的更新。
标签: javascript angular performance typescript for-loop