const test = [
{ title: 'Название 1', id: 4 },
{ title: 'Название 2', id: 2 },
{ title: 'Название 3', id: 3 },
{ title: 'Название 4', id: 1 },
];
const testResult = [
{ id: 1, count: 234 },
{ id: 2, count: 344 },
{ id: 3, count: 5678 },
{ id: 4, count: 3421 },
];
const testResult = [
{ id: 1, count: 234, title: 'Название 4' },
{ id: 2, count: 344 , title: 'Название 3' },
{ id: 3, count: 5678, title: 'Название 2' },
{ id: 4, count: 3421, title: 'Название 1' },
];
function merge(key, ...arrs) {
const getKey = key instanceof Function ? key : n => n[key];
const result = new Map;
arrs.forEach(arr => arr.forEach(n => {
const k = getKey(n);
result.set(k, Object.assign(result.get(k) ?? {}, n));
}));
return [...result.values()];
}
const result = merge('id', testResult, test);
function merge(key, target, ...arrs) {
const getKey = key instanceof Function ? key : n => n[key];
const targetMap = new Map(target.map(n => [ getKey(n), n ]));
arrs.forEach(arr => arr.forEach(n => {
const k = getKey(n);
targetMap.has(k) && Object.assign(targetMap.get(k), n);
}));
return target;
}
merge(n => n.id, testResult, test);
const newTestResult = testResult.map(item => ({
...item,
title: test.find(subItem => subItem.id === item.id)?.title,
}));
console.log(newTestResult);