数据如下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}]
2 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
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)
添加回答
举报
0/150
提交
取消