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)
过去多啦不再A梦2017-05-16 13:34:36
The reason is that each attribute of obj used for judgment has been calculated once, and conditional blocking can be added to improve it:
var convert = function(obj) {
return obj.map(o => ({
'number': o.type === 'number ' && 1,
'string': o.type === 'string ' && 's',
'array': o.type === 'array ' && convert(o.children)
}[o.type]))
}
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.
習慣沉默2017-05-16 13:34:36
The error is that there are no children when the first one is reported
var convert = function(obj) {
return obj.map(o => ({
'number': 1,
'string': 's',
'array': o.children?convert(o.children):""//假设没有的时候返回空咯
}[o.type]))
}