Здесь идея:
- Сначала измените второй массив на объект, чтобы стало легче находить значения в нем
- Теперь переберите массив 1 и возьмите соответствующих потомков из массива 2
- Цикл для потомков массива1 и изменение значения в соответствии с потомками из массива2
const arr1 = [{"name":"Category 1","value":"Vegetables","children":[{"name":"Carrots","value":"Carrots","count":2},{"name":"Peas","value":"Peas","count":1}]},{"name":"Category 2","value":"Fruits","children":[{"name":"Apples","value":"Apples","count":10},{"name":"Bananas","value":"Bananas","count":5}]},{"name":"Category 3","value":"Desserts","children":[{"name":"Ice Cream","value":"IceCream","count":3},{"name":"Cakes","value":"Cakes","count":3}]}];
const arr2 = [{"name":"Category 1","value":"Vegetables","children":[{"name":"Peas","value":"Peas","count":1}]},{"name":"Category 2","value":"Fruits","children":[{"name":"Apples","value":"Apples","count":3},{"name":"Bananas","value":"Bananas","count":2}]},{"name":"Category 3","value":"Desserts","children":[]}];
let arr2Obj = Object.fromEntries(arr2.map(val => [val.name, val]))
const res = arr1.map(({ name, value, children }) => {
let arr2Children = ( arr2Obj[name] || {} ).children
let childrenObj = Object.fromEntries(arr2Children.map(val => [val.name,val]))
let newChildren = children.map( val => {
let count = (childrenObj[val.name] || {}).count || 0
return {...val,count}
})
return {name,value,children:newChildren}
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
PS: - Если ваши массивы1 и массив2 всегда отсортированы, вам не нужно менять их объект, и вы можете получить прямой доступиспользуя индекс, то же самое для детей
const arr1 = [{"name":"Category 1","value":"Vegetables","children":[{"name":"Carrots","value":"Carrots","count":2},{"name":"Peas","value":"Peas","count":1}]},{"name":"Category 2","value":"Fruits","children":[{"name":"Apples","value":"Apples","count":10},{"name":"Bananas","value":"Bananas","count":5}]},{"name":"Category 3","value":"Desserts","children":[{"name":"Ice Cream","value":"IceCream","count":3},{"name":"Cakes","value":"Cakes","count":3}]}];
const arr2 = [{"name":"Category 1","value":"Vegetables","children":[{"name":"Peas","value":"Peas","count":1}]},{"name":"Category 2","value":"Fruits","children":[{"name":"Apples","value":"Apples","count":3},{"name":"Bananas","value":"Bananas","count":2}]},{"name":"Category 3","value":"Desserts","children":[]}];
let createObject = (arr) => arr.reduce((op,[key,value])=>{
op[key] = value
return op
},{})
let arr2Obj = createObject(arr2.map(val => [val.name, val]))
const res = arr1.map(({ name, value, children }) => {
let arr2Children = ( arr2Obj[name] || {} ).children
let childrenObj = createObject(arr2Children.map(val => [val.name,val]))
let newChildren = children.map( val => {
let count = (childrenObj[val.name] || {}).count || 0
return {...val,count}
})
return {name,value,children:newChildren}
});
console.log(res);