Notes for a front-end developer, esyou.net

0%

JAVASCRIPT将有相同内容的数组或对象的值进行累加

我们可能会经常遇到如下这样的问题,就像我们的后端要从数据库中读取相同id的内容,并且合并相同id已有的值。

1
var arry = [{
2
        pid:123,
3
        info: '男'
4
    },{
5
        pid:123,
6
        info:'女'
7
    },{
8
        pid:123,
9
        info: '未知'
10
    },{
11
        pid:456,
12
        info: '东'
13
    },{
14
        pid:456,
15
        info:'西'
16
    },{
17
        pid:456,
18
        info: '南'
19
    },{
20
        pid:456,
21
        info: '北'
22
    }
23
]

我们看到以上数组对象中,可以看到有很多个相同pid的属性值,我的目的就是将其相同的pid值的对象的info值全部合并起来,诸如

1
[{pid:123,info:'男/女/未知'},{pid:456,info:'东/西/南/北'}]

也就是说将相同的pid的相关内容进行合并。

使用reduce方法

1
let newArr = arry.sort((pre, next) => pre.pid > next.pid).reduce((pre, v) => {
2
  let lastIndex = pre.length - 1;
3
  if (lastIndex >= 0 && pre[lastIndex].pid === v.pid) {
4
    pre[lastIndex].info += v.info;
5
  } else {
6
    pre.push(Object.assign({}, v));
7
  }
8
  return pre;
9
}, []);
10
console.log(newArr);

这种方法确实挺不错,也很容易理解,但是不确定是否会对性能造成问题。另外就是对中文的支持并不好!很有可能我们会得到如下内容

1
[{pid:123,info:'男'},{pid:456,info:'东/西/南/北'}]

因此,建议使用另一种遍历的方式进行处理

foreach遍历

使用遍历,并采用hasOwnProperty判断属性,对象拷贝等实现

1
let res = [];
2
let tmp = {};
3
arr.forEach((v) => {
4
  if (!tmp.hasOwnProperty(v.pid)) {
5
    tmp[v.pid] = res.length;
6
    return res.push(Object.assign({}, v));
7
  }
8
  res[tmp[v.code]].info += v.info;
9
});
10
11
return res; //printer [{pid:123,info:'男/女/未知'},{pid:456,info:'东/西/南/北'}]