KVN*_*VNA 2 javascript arrays sorting grouping
我正在尝试按值将数组转换为一组新的数组,在本例中为id.
输入
let array = [
{"item": {"id": 111, "name": "item1"}, "qty": 1},
{"item": {"id": 222, "name": "item2"}, "qty": 2},
{"item": {"id": 222, "name": "item3"}, "qty": 3}
];
Run Code Online (Sandbox Code Playgroud)
期望输出
let newArray = [
[{"item": {"id": 111, "name": "item1"}, "qty": 1}],
[{"item": {"id": 222, "name": "item2"}, "qty": 2},
{"item": {"id": 222, "name": "item3"}, "qty": 3}]
];
Run Code Online (Sandbox Code Playgroud)
使用标准groupBy函数,我们可以返回两个按 排序的数组id。
function groupItemBy(array, property) {
var hash = {};
for (var i = 0; i < array.length; i++) {
if (!hash[array[i][property]]) hash[array[i][property]] = [];
hash[array[i][property]].push(array[i]);
}
return hash;
}
Run Code Online (Sandbox Code Playgroud)
但是,当尝试将这些映射到新数组时,嵌套qty数据会丢失。
function parse() {
let tmp = Object.values(groupItemBy(array.map(el => el.item), "id"));
tmp.forEach(item => {
console.log(item);
// do something with each item in array
})
}
Run Code Online (Sandbox Code Playgroud)
实际产量
let newArray = [
[{{"id": 111, "name": "item1"}],
[{"id": 222, "name": "item2"},
{"id": 222, "name": "item3"}]
];
Run Code Online (Sandbox Code Playgroud)
在将原始数组分组为已排序数组的数组时,如何保持关联数据的完整性?
为此,您必须以某种方式告诉函数 key 属性所在的位置。可以想象非常复杂的嵌套对象,并且几个可能具有相同的属性名称,因此如果没有这样的规范,它甚至可能导致歧义。
解决这个问题的一种方法是让函数知道点分隔的属性(在一个字符串中)——一种“路径”。在你的情况下,那将是item.id. 有了这些信息,函数就可以知道在哪里寻找id值(在嵌套对象中item)。
显然,该函数将通过这些点分割该字符串。然后它可以reduce对生成的属性名称数组执行 a以定位数组中每个对象的键值。
这是它的样子:
let cart = [{"item": {"id": 111,"name": "item1", }, "qty": 10,}, {"item": {"id": 222,"name": "item2"},"qty": 1}, {"item": {"id": 222,"name": "item3"},"qty": 1,}];
function groupItemBy(array, property) {
var hash = {},
props = property.split('.');
for (var i = 0; i < array.length; i++) {
var key = props.reduce(function(acc, prop) {
return acc && acc[prop];
}, array[i]);
if (!hash[key]) hash[key] = [];
hash[key].push(array[i]);
}
return hash;
}
let grouped = Object.values(groupItemBy(cart, 'item.id'));
console.log(grouped);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3665 次 |
| 最近记录: |