Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

这组数据中 怎么把name的值相同的number相加?
原数据

var res = [{
    "name": "apple",
    "number": "15",
    "date": "2017/1/2",
}, {
    "name": "orange",
    "number": "25",
    "date": "2017/1/4",
}, {
    "name": "apple",
    "number": "4",
    "date": "2017/1/7",
}, {
    "name": "banana",
    "number": "1",
    "date": "2017/1/1",
}];

希望统计的结果

var res = [{
    "name": "apple",
    "number": "19",
}, {
    "name": "orange",
    "number": "25",
}, {
    "name": "banana",
    "number": "1",
}];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
325 views
Welcome To Ask or Share your Answers For Others

1 Answer

注意number 是个字符串

let tmp = {}
res.forEach(v => tmp[v.name] = (tmp[v.name] || 0) + Number(v.number))
res = Object.keys(tmp).map(name => ({ name, number: tmp[name]}))
console.log(res)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...