我的角度应用程序中有此回复。我必须减少代码。
res=[
{ "url": "/page1", "views": 2 },
{ "url": "/page2", "views": 1 },
{ "url": "/page1", "views": 10 },
{ "url": "/page2", "views": 4 },
{ "url": "/page3", "views": 1 },
{ "url": "/page2", "views": 0 },
{ "url": "/page3", "views": 14 },
{ "url": "/page1", "views": 04 },
{ "url": "/page3", "views": 14 },
]
,我需要像
这样的最终答复res=[
{ "url": "/page1", "views": 104 },
{ "url": "/page2", "views": 104 },
{ "url": "/page3", "views": 104 },
]
答案 0 :(得分:0)
您可以使用简单的reduce
操作:
var res = [
{ "url": "/page1", "views": 2 },
{ "url": "/page2", "views": 1 },
{ "url": "/page1", "views": 10 },
{ "url": "/page2", "views": 4 },
{ "url": "/page3", "views": 1 },
{ "url": "/page2", "views": 0 },
{ "url": "/page3", "views": 14 },
{ "url": "/page1", "views": 04 },
{ "url": "/page3", "views": 14 },
];
res = res.reduce((val, acc) => {
if (acc.some(e => e.url == val.url)) {
acc.find(e => e.url == val.url).views += val.views;
} else {
acc.push({
url: val.url,
views: val.views,
});
}
return acc;
}, []);
console.log(res);
答案 1 :(得分:0)
使用数组reduce()
var result = res.reduce((accu, obj) => {
accu[obj.url] = (accu[obj.url] || 0) + obj.views;
return accu;
},
{}
);
节点CLI的输出:
> var result = res.reduce((accu, obj) => { accu[obj.url] = (accu[obj.url] || 0) + obj.views; return accu; }, {});
undefined
> result
{ '/page1': 16, '/page2': 5, '/page3': 29 }
答案 2 :(得分:0)
接受的答案返回一个对象。您可以使用reduce
做这样的事情以获得所需的输出:
const res=[{"url":"/page1","views":2},{"url":"/page2","views":1},{"url":"/page1","views":10},{"url":"/page2","views":4},{"url":"/page3","views":1},{"url":"/page2","views":0},{"url":"/page3","views":14},{"url":"/page1","views":04},{"url":"/page3","views":14}],
merged = res.reduce((acc,{url,views})=> {
acc[url] = acc[url] || {url, views:0}
acc[url].views += views;
return acc;
}, {}),
output = Object.values(merged)
console.log(output)
以下是上述代码的简化版本:
const res=[{"url":"/page1","views":2},{"url":"/page2","views":1},{"url":"/page1","views":10},{"url":"/page2","views":4},{"url":"/page3","views":1},{"url":"/page2","views":0},{"url":"/page3","views":14},{"url":"/page1","views":04},{"url":"/page3","views":14}],
output = res.reduce((acc,{url,views})=>
((acc[url] = acc[url] || {url, views:0})["views"] += views, acc), {})
console.log(Object.values(output))
另一个使用Map
const res=[{"url":"/page1","views":2},{"url":"/page2","views":1},{"url":"/page1","views":10},{"url":"/page2","views":4},{"url":"/page3","views":1},{"url":"/page2","views":0},{"url":"/page3","views":14},{"url":"/page1","views":04},{"url":"/page3","views":14}],
map = res.reduce((m,{url,views})=> {
const o = m.get(url) || {url,views:0};
o.views += views;
return m.set(url, o);
}, new Map),
output = [...map.values()];
console.log(output)