根据数组对象的属性值获取资格

时间:2019-07-09 13:06:23

标签: javascript arrays

我需要基于属性(idInteraction)的值获取资格的总和。我应该如何迭代?

我曾尝试根据能力订单进行迭代,但无法匹配idInteraction。

var arrayQ = [
    '{"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":1, "qualification":40}',
    '{"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":2, "qualification":60}', 
    '{"idInteraction":"{8ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":1, "qualification":20}', 
    '{"idInteraction":"{8ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":2, "qualification":30}'
];

var q = 0;

function findMinMax(arr) {
    let min = JSON.parse(arr[0]).abilityOrder,
        max = JSON.parse(arr[0]).abilityOrder;
    for (let i = 1, len = arr.length; i < len; i++) {
        let v = JSON.parse(arr[i]).abilityOrder;
        min = (v < min) ? v : min;
        max = (v > max) ? v : max;
    }
    return [min, max];
}

var maxAbility = findMinMax(arrayQ);

arrayQ.forEach(function(result, index) {
    result = JSON.parse(result);

    let i = 0;
    if (i <= maxAbility[1] && result.idInteraction) {
        q = q + result.qualification;
        console.log('id..' + result.idInteraction + 'q..' + q);
        q = 0;
    }
});

预期结果是:

"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}" - q = 100
"idInteraction":"{8ae8653e-99ef-11e9-9e08-90c283d38b9a}" - q = 50

有什么建议吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以简单地使用reduce来获得按idInteraction值分组的总和:

const arrayQ = ['{"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":1, "qualification":40}', '{"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":2, "qualification":60}', '{"idInteraction":"{8ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":1, "qualification":20}', '{"idInteraction":"{8ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":2, "qualification":30}'];

const res = arrayQ.map(e => JSON.parse(e))
    .reduce((a, b) => a.set(b.idInteraction, ~~ a.get(b.idInteraction) + b.qualification), new Map);

console.log(res); // open the console. SO can't show Maps
console.log(Array.from(res));