2

我正在寻找一种方法来整合 javascript 中的对象集合。例如我有一个集合:

inventory = [ 
    {count: 1, type: "Apple"},
    {count: 2, type: "Orange"},
    {count: 1, type: "Berry"},
    {count: 2, type: "Orange"},
    {count: 3, type: "Berry"}
]

我想要结束的是:

   inventory = [
        {count: 1, type: "Apple"},
        {count: 4, type: "Orange"},
        {count: 4, type: "Berry"}
     ]

有没有一种优雅的方法可以做到这一点,它不涉及获取类型列表、在我的集合中搜索这些类型、对值求和以及用总和创建一个新数组?

4

3 回答 3

3

它并不过分漂亮,但这会做到这一点。它创建了一个项目类型/计数的字典和一个最终总和的列表。inventoryDict用于轻松找到现有计数,同时summedInventory保存总和项目的最终列表。

var inventory = [ /* ... */ ];
var summedInventory = [];
var inventoryDict = {};

for (var i = 0; i < inventory.length; i++) {
    var item = inventory[i];
    if (!(item.type in inventoryDict)) {
        inventoryDict[item.type] = {type: item.type, count: 0};
        summedInventory.push(inventoryDict[item.type]);
    }
    inventoryDict[item.type].count += item.count;
}

这是假设您不想改变库存物品 - 如果您不介意改变物品,可以稍微简化循环。

为了避免中间变量并以更实用的方式执行,您可以使用 Array.reduce:

var newInventory = inventory.reduce(function(acc, item) {
    var summedInventory = acc[0], inventoryDict = acc[1];

    if (!(item.type in inventoryDict)) {
        inventoryDict[item.type] = {type: item.type, count: 0};
        summedInventory.push(inventoryDict[item.type]);
    }

    inventoryDict[item.type].count += item.count;
    return acc;
}, [[], {}])[0];
于 2013-11-13T05:45:26.003 回答
1

我的解决方案是这样的:

inventory = [ 
    {count: 1, type: "Apple"},
    {count: 2, type: "Orange"},
    {count: 1, type: "Berry"},
    {count: 2, type: "Orange"},
    {count: 3, type: "Berry"}
];

result = {};
inventory.map(function(item) {
    console.log(item);
    var count = result[item.type] || 0;
    result[item.type] = item.count + count;
});

inventory = [];

for (property in result) {
    inventory.push({count: result[property], type: property});
}

console.log(inventory);

看到这个 jsfiddle

于 2013-11-13T06:00:42.773 回答
1

这是使用 Javascript 的Array.reduce的一种相对简单的方法:

var reduced = inventory
    .reduce(function(sum,current) {
        var found = false
        sum.forEach(function(row,i) {
            if (row.type === current.type) {
                sum[i].count += current.count
                found = true;
            }
        })
        if (found === false) sum.push(current)
        return sum
    }, [])

console.log(reduced)
于 2013-11-13T06:12:41.847 回答