我试图让一个数组(from)变得像(to)。要在我使用的匹配数组值中排除'qtty':
_.isEqual(_.omit(val, 'qtty'), _.omit(value2, 'qtty'))
来自http://underscorejs.org/#isEqual它给出了正确的结果,但我无法得到最终结果。
From =
0 {itemId: "121", qtty: 1, subitem: [], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []}
1 {itemId: "121", qtty: 1, subitem: [], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []}
2 {itemId: "121", qtty: 1, subitem: [{subitemId: 72, state: 1}], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []}
3 {itemId: "141", qtty: 1, subitem: [], combo: [{comboId: 201, setId: 26}], addon: []}
4 {itemId: "347", qtty: 1, subitem: [], combo: [], addon: []}
5 {itemId: "347", qtty: 1, subitem: [], combo: [], addon: []}
To =
0 {itemId: "121", qtty: 2, subitem: [], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []}
1 {itemId: "121", qtty: 1, subitem: [{subitemId: 72, state: 1}], combo: [{comboId: 201, setId: 29}, {comboId: 201, setId: 28}], addon: []}
2 {itemId: "141", qtty: 1, subitem: [], combo: [{comboId: 201, setId: 26}], addon: []}
3 {itemId: "347", qtty: 2, subitem: [], combo: [], addon: []}
答案 0 :(得分:0)
我找到答案here感谢Gruff Bunny发布了答案,但需要进行一些调整才能使其与我的案例一样使用更多维数组。
function unify(orderData) {
var groups = _.groupBy(orderData, function (value) {
return value.itemId + '#' + _.map(value.subitem, function (subitemValue) { return subitemValue.subitemId + '#' + subitemValue.state ; }) + '#' + _.map(value.addon, function (addonValue) { return addonValue.addonId + '#' + addonValue.state; }) + '#' + _.map(value.combo, function (comboValue) { return comboValue.comboId + '#' + comboValue.setId; }) ;
});
var data = _.map(groups, function (group) {
return {
itemId: group[0].itemId,
subitem: group[0].subitem,
addon: group[0].addon,
combo: group[0].combo,
qtty: _.reduce(_.pluck(group, 'qtty'), function (memo, num) {
return memo + num;
}, 0)
}
});
return data;
}
这里的主要区别是将_.map()
映射到每个子阵列,以便能够通过复杂的多维数组进行分组。