My mind is boggled, maybe because i've been stuck on this issue for a bit.
I have an array (redacted for readability):
variants = [
{title: 'color', children: [{title: 'red'}, {title: 'blue'}]
{title: 'size', children: [{title: 'large'}]
]
But need the following output:
variants = [
'color/red/size/large',
'color/blue/size/large',
]
or if the initial array is:
variants = [
{title: 'color', children: [{title: 'red'}, {title: 'blue'}]
{title: 'size', children: [{title: 'large'}, {title: 'medium'}]
]
the new array would be:
variants = [
'color/red/size/large',
'color/blue/size/large',
'color/red/size/medium',
'color/blue/size/medium',
]
Here is a fairly succinct reduce, but it has a nested flatMap(() => map())
call in its midst so I can't vouch for its efficiency.
const variants = [ { title: 'color', children: [{ title: 'red' }, { title: 'blue' }] }, { title: 'size', children: [{ title: 'large' }, { title: 'medium' }] }, ] variants.sort((a, b) => b.children.length - a.children.length); const out = variants.reduce((acc, { title, children }) => { const props = children.map(({ title: child }) => `${title}/${child}`); acc = acc.length === 0? props: acc.flatMap(a => props.map(p => `${a}/${p}`)); return acc; }, []) console.log(out)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.