javascript - 根据 1 个特定值的标识将对象拆分为多个有序数组

标签 javascript arrays sorting

不太确定这个标题是否是我能做的最好的。

我是 js 的新手,经常遇到问题......我希望你们中的一些人有时间就这种情况给我一两个建议。

我有几个对象看起来很像这个 - 除了每个“房间”类型有 28 个实例之外。我需要将此对象拆分为多个对象 - 每个“房间”类型一个。在我的一些对象中只有一种房间类型 - 而在其他对象中有 3 种或 4 种。

[   { id: 1
  created: 2018-12-29T13:18:05.788Z,
  room: 'Double Room'
  type: 'Standard'
  price: 500 
},
{ id: 29
  created: 2018-12-29T13:18:05.788Z,
  room: 'Twin Room'
  type: 'Standard'
  price: 500 
},
{ id: 58
  created: 2018-12-29T13:18:05.788Z,
  room: 'Family Room'
  type: 'Standard'
  price: 900 
},
]

哦,重要的是实例不要“松散”它们在数组中的顺序 - 因为它与日期相关并且需要按升序显示。并且仅限 Vanilla js。

array.map() 是我正在寻找的函数来解决这个问题吗?没有迭代就可以做到这一点吗?

我的最终目标是创建某种通用函数来为我的所有对象解决这个问题。

各位:节日快乐!

最佳答案

您可以将一个对象作为所需组的哈希表。然后迭代对象并将对象分配给组。如果该组不存在,则使用数组创建一个新组。

function groupBy(array, key) {
    var groups = Object.create(null);
    array.forEach(o => (groups[o[key]] = groups[o[key]] || []).push(o));
    return groups;
}

var data = [{ id: 1, created: '2018-12-29T13:18:05.788Z', room: 'Double Room', type: 'Standard', price: 500 }, { id: 29, created: '2018-12-29T13:18:05.788Z', room: 'Twin Room', type: 'Standard', price: 500 }, { id: 58, created: '2018-12-29T13:18:05.788Z', room: 'Family Room', type: 'Standard', price: 900 }],
    groupedByRoom = groupBy(data, 'room');

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

关于javascript - 根据 1 个特定值的标识将对象拆分为多个有序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53972264/

相关文章:

javascript - 将 "then"方法添加到 $promise 链中预定义的 "finally"方法之前

javascript - 与 not() 函数相反

excel - 计算同一工作簿中不同工作表中不同列中特定颜色文本的单元格

javascript - JS 方法绑定(bind) 2 个不同的 this

javascript - 当目标位于顶部滚动时,如何激活菜单中的项目?

c - Objective C 中的指针,从函数返回指针

Javascript - 通过键获取特定 JSON 数组元素中属性的值

java - 从数组中的字符串获取索引

java - 如何返回给定 HashMap 的有序列表?

c++ - 对 std::pair 的 vector 进行排序