计算具有相同值的实例

时间:2015-01-22 22:22:47

标签: javascript

对于一个项目,我需要在JavaScript中进行一些数据操作。

我需要转换此对象:

[
        {"source":"stkbl0001","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0003","target":"stkbl0005"},
        {"source":"stkbl0004","target":"stkbl0005"},
        {"source":"stkbl0004","target":"stkbl0005"}
]

到这个对象:

[
    {"source":"stkbl0001","target":"stkbl0005","value":1},
    {"source":"stkbl0002","target":"stkbl0005","value":5},
    {"source":"stkbl0003","target":"stkbl0005","value":1},
    {"source":"stkbl0004","target":"stkbl0005","value":2}
]

(注意第一个对象中的某些元素是相同的,而新字段value包含重复次数)

基本上,我需要检测并计算多个实例,并创建包含多个实例的新字段value

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以跟踪对象:

var obj = {};
var result = [];

for (var i = 0; i < arr.length; i++) {
  var item = arr[i],
      key = item.source + '-' + item.target;
  if (obj.hasOwnProperty(key)) obj[key].value++;
  else {
     obj[key] = item;
     item.value = 1;
  }
}

for (var prop in obj) {
  result.push(obj[prop]);
}

在此示例中,假设arr是您的原始数组,而result是您生成的数组。

result最终将成为具有sourcetarget属性的唯一组合的对象数组,而value将是遇到这些组合的数字。