如何将对象数组转换为更高级的数组

时间:2018-09-04 08:22:51

标签: javascript arrays node.js object reduce

我正在寻找JS中我的小问题的解决方案。 我有对象数组

[
 { "id": "id-1", "weight": 345 },
 { "id": "id-2", "weight": 500 },
 { "id": "id-3", "weight": 300 }
]

我想得到图片上的数组

[
  {
    "orderID" : "uniqueID",
    "load" : [
       { "id" "id-1", "weight": 345 },
       { "id" "id-2", "weight": 500 },
    ]
  },
  {
    "orderID" : "uniqueID",
    "load" : [
       { "id" "id-3", "weight": 300 }
    ]
  }
]

我想将包裹分成多个负载(每个负载不超过1000重量)

1 个答案:

答案 0 :(得分:0)

您可以使用array.reduce进行分组:

var arr = [
 { "id": "id-1", "weight": 345 },
 { "id": "id-2", "weight": 500 },
 { "id": "id-3", "weight": 300 }
];

var res = arr.reduce((m, o, i) => {
    var lastPushedElement = m[m.length - 1];
    var totLoad = lastPushedElement.load.reduce((s, e) => s + e.weight, 0);
    if ((totLoad + o.weight) <= 1000) {
        lastPushedElement.load.push(o);
    } else {
        m.push({ orderID: i + 1, load: [o] });
    }
    return m;
}, [{ orderID: 0, load: [] }]);

console.log(res);