Answer the question
In order to leave comments, you need to log in
How to do recursion in this case?
There is an array
var products = [
{
name: 'pac1',
packingLevel: 1,
childItems: [
{
name: 'prod1',
packingLevel: 0,
},
{
name: 'prod2',
packingLevel: 0,
}
]
},
{
name: 'pac2',
packingLevel: 2,
childItems: [
{
name: 'upac1',
packingLevel: 1,
childItems: [
{
name: 'prod01',
packingLevel: 0,
},
{
name: 'prod02',
packingLevel: 0,
}
]
},
{
name: 'prod2',
packingLevel: 0,
}
]
},
{
name: 'prod11'
},
];
var packing = [
{
name: 'prod1',
packingLevel: 1,
childItems: [
{
name: 'pac1',
packingLevel: 0,
}
]
},
{
name: 'prod2',
packingLevel: 1,
childItems: [
{
name: 'pac1',
packingLevel: 0,
}
]
},
{
name: 'prod01',
packingLevel: 2,
childItems: [
{
name: 'upac1',
packingLevel: 1,
childItems: [
{
name: 'pac2',
packingLevel: 0,
}
]
}
]
},
{
name: 'prod02',
packingLevel: 2,
childItems: [
{
name: 'upac1',
packingLevel: 1,
childItems: [
{
name: 'pac2',
packingLevel: 0,
}
]
}
]
},
{
name: 'prod11'
},
];
Answer the question
In order to leave comments, you need to log in
Helper function, very necessary, don't ask why:
const getReversedPaths = (arr, path = []) =>
arr.reduce((acc, { childItems, ...item }) => {
path.push(item);
if (childItems) {
acc.push(...getReversedPaths(childItems, path));
} else {
acc.push(path.length > 1
? path.map(({ packingLevel }, i, a) => ({ ...a[a.length - i - 1], packingLevel }))
: [ path[0] ]
);
}
path.pop();
return acc;
}, []);
const reverseThere = arr =>
getReversedPaths(arr).map(n =>
n.reduceRight((child, parent) => ({ ...parent, childItems: [ child ] }))
);
const reverseBackAgain = arr =>
(function createTree(arr) {
return Object.values(arr.reduce((acc, [ head, ...tail ]) => {
if (tail.length) {
(acc[head.name] = acc[head.name] || { ...head, childItems: [] }).childItems.push(tail);
} else {
acc[head.name] = head;
}
return acc;
}, {})).map(n => (n.childItems && (n.childItems = createTree(n.childItems)), n));
})(getReversedPaths(arr));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question