添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接


数据如下

var arr = [{name: "上海", value: 1},{name: "上海", value: 2},{name: "北京", value: 3},{name: "杭州", value: 2}]

想要得到的json数据

arr = [{name: "上海", value: 3},{name: "北京", value: 3},{name: "杭州", value: 2}]

实现方法

function trans (arr) {
let obj = {}
let result = []
arr.forEach(({name, value}) => {
let cur = obj[name]
if (cur) {
let index = cur.index
result[index].value += value
} else {
let index = result.length
obj[name] = {
name,
index
}
result.push({name, value})
}
})
return result
}
var arr = [{name: "上海", value: 1},{name: "上海", value: 2},{name: "北京", value: 3},{name: "杭州", value: 2}]
trans(arr)