var obj = [
{ type: 'number' },
{ type: 'string' },
{
type: 'array',
children: [
{ type: 'number' },
{ type: 'string' }
]
}
]
var convert = function(obj) {
return obj.map(o => ({
'number': 1,
'string': 's',
'array': convert(o.children)
}[o.type]))
}
var convert2 = function(obj) {
return obj.map(o => {
if (o.type === 'number') {
return 1
} else if (o.type === 'string') {
return 's'
} else if (o.type === 'array') {
return convert2(o.children)
} else {
return undefined
}
})
}
var converted = convert(obj)
var converted2 = convert2(obj)
The reason is that each attribute of obj used for judgment has been calculated once, and conditional blocking can be added to improve it:
When there are few conditions to be judged, you can use multiple trinocular conditions to judge. If there are too many such judgments, this writing method should be more beautiful. If you cannot accept it, you may have to write if else.
Because your recursion has no termination condition
The error is that there are no children when the first one is reported