javascript:操纵对象数组

时间:2016-08-23 08:25:17

标签: javascript arrays performance

我有一个这样的数组:

arr = [
  {name:'Tom', a:1, b:1, c:0},
  {name:'Sam', a:0, b:1, c:1},
  {name:'Tom', a:0, b:0, c:1},
  {name:'Sam', a:1, b:2, c:1},
  {name: 'Jack', a:1, b:2, c:0}
]

我需要将具有相同名称的对象的属性相加,然后对重复项进行切片:

arr = [
  {name:'Tom', a:1, b:1, c:1},
  {name:'Sam', a:1, b:3, c:2},
  {name: 'Jack', a:1, b:2, c:0}
]

纯JavaScript中怎么可能?

3 个答案:

答案 0 :(得分:1)

for loop Array#splice 与对象一起用于索引参考。

// object reference for index
var obj = {},
  //  variable for delete count
  dc = 0,
  // variable for length of array
  len = arr.length;

// iterate over the object array
for (var i = 0; i < len; i++) {
  // get the current object
  var v = arr[i - dc];
  // check property defined in reference object
  if (obj.hasOwnProperty(v.name)) {
    // if already defined add the values
    arr[obj[v.name]].a += v.a;
    arr[obj[v.name]].b += v.b;
    arr[obj[v.name]].c += v.c;
    // if there is random properties are there then use 
    // Object.keys to get the property name value array
    // and iterate and update the properties ( except `name` )

    // remove the current element and increment delete count
    arr.splice(i - dc++, 1);
  } else {
    // else define the index reference in object
    obj[v.name] = i - dc;
  }
}

&#13;
&#13;
var arr = [{
  name: 'Tom',
  a: 1,
  b: 1,
  c: 0
}, {
  name: 'Sam',
  a: 0,
  b: 1,
  c: 1
}, {
  name: 'Tom',
  a: 0,
  b: 0,
  c: 1
}, {
  name: 'Sam',
  a: 1,
  b: 2,
  c: 1
}, {
  name: 'Jack',
  a: 1,
  b: 2,
  c: 0
}];

var obj = {},
  dc = 0,
  len = arr.length;

for (var i = 0; i < len; i++) {
  var v = arr[i - dc];
  if (obj.hasOwnProperty(v.name)) {
    arr[obj[v.name]].a += v.a;
    arr[obj[v.name]].b += v.b;
    arr[obj[v.name]].c += v.c;
    arr.splice(i - dc++, 1);
  } else {
    obj[v.name] = i - dc;
  }
}

console.log(arr);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

随机属性的提议,带有哈希表。

var arr = [{ name: 'Tom', a: 1, b: 1, c: 0 }, { name: 'Sam', a: 0, b: 1, c: 1 }, { name: 'Tom', a: 0, b: 0, c: 1 }, { name: 'Sam', a: 1, b: 2, c: 1 }, { name: 'Jack', a: 1, b: 2, c: 0 }],
    grouped = [];

arr.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { name: a.name };
        grouped.push(this[a.name]);
    }
    Object.keys(a).forEach(function (k) {
        if (k !== 'name') {
            this[k] = (this[k] || 0) + a[k];
        }
    }, this[a.name]);
}, Object.create(null));

console.log(grouped);

答案 2 :(得分:0)

创建第二个数组。然后,对于第一个数组的每个元素,迭代第一个数组并将属性的总和推送到新数组。在每个副本上,您必须删除第一个数组中的条目。并且tada ...