[
{ "user_id": 1, "page_views": 7, "clicks": 5 },
{ "user_id": 5, "page_views": 6, "clicks": 3 },
{ "user_id": 9, "page_views": 4, "clicks": 7 },
{ "user_id": 1, "page_views": 3, "clicks": 5 },
]
[
{"id":9,"first_name":"Barnabas"},
{"id":1,"first_name":"Emlyn"},
{"id":5,"first_name":"Ervin"},
]
[
{"id":9, "first_name":"Barnabas", "page_views": 4 , "clicks": 7 },
{"id":1, "first_name":"Emlyn", "page_views": 10, "clicks": 10 },
{"id":5, "first_name":"Ervin", "page_views": 7, "clicks": 5 },
]
Object.values(arr1.reduce((acc, { user_id: id, ...n }) => {
Object.entries(n).forEach(([ k, v ]) => acc[id][k] = (acc[id][k] || 0) + v);
return acc;
}, Object.fromEntries(arr2.map(n => [ n.id, {...n} ]))))
Map
:[...arr1.reduce((acc, { user_id: id, ...n }) => {
const obj = acc.get(id);
Object.entries(n).forEach(([ k, v ]) => obj[k] = (obj[k] || 0) + v);
return acc;
}, new Map(arr2.map(n => [ n.id, {...n} ]))).values()]
Object.values
извлекаем данные из объекта через map
по исходному массиву:arr2.map(function(n) {
return this[n.id];
}, arr1.reduce((acc, { user_id: id, ...n }) => (
Object.keys(n).forEach(k => acc[id][k] = (acc[id][k] || 0) + n[k]),
acc
), Object.fromEntries(arr2.map(n => [ n.id, {...n} ]))))
const array1 = [
{ "user_id": 1, "page_views": 7, "clicks": 5 },
{ "user_id": 5, "page_views": 6, "clicks": 3 },
{ "user_id": 9, "page_views": 4, "clicks": 7 },
{ "user_id": 1, "page_views": 3, "clicks": 5 },
];
const array2 = [
{"id":9,"first_name":"Barnabas"},
{"id":1,"first_name":"Emlyn"},
{"id":5,"first_name":"Ervin"},
];
const result = array2.map(item2 => {
// отфильтровали массив 1 на наличие элементов с соответствующим id
const withCurrentId = array1.filter(item1 => item1['user_id'] === item2['id']);
// склеили новый объект с суммами свойств
const item1 = withCurrentId.reduce((acc, curr) => {
// если в аккумуляторе нет свойства page_views, то 0, потом суммируем
acc['page_views'] = (acc['page_views'] || 0) + curr['page_views'];
// если в аккумуляторе нет свойства clicks, то 0, потом суммируем
acc['clicks'] = (acc['clicks'] || 0) + curr['clicks'];
return acc;
}, {});
return { ...item2, ...item1 };
});
console.log(result);
let result = users.reduce(
(acc, val) => {
acc[val.id] = {
id: val.id,
first_name: val.first_name,
page_views: 0,
clicks: 0
};
return acc;
},
[]
);
result = views.reduce(
(acc, val) => {
acc[val.user_id].page_views += val.page_views;
acc[val.user_id].clicks += val.clicks;
return acc;
},
result
);
result = result.filter(x => x);
for (let i in users) {
for (let j in views) {
if (users[i].id === views[j].user_id) {
if (users[i].hasOwnProperty('page_views')) {
users[i].page_views += views[j].page_views;
users[i].clicks += views[j].clicks;
}
else {
users[i].page_views = views[j].page_views;
users[i].clicks = views[j].clicks;
}
}
}
}