-
-
Save zackexplosion/8ff0a03078c3bab967632e8b6a899480 to your computer and use it in GitHub Desktop.
裝B攤平法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var obj = { | |
"name" : { | |
full_name: 'Hello', | |
given: ['a name', 'b name', 'c name'] | |
}, | |
"tel" : { | |
phone: '0000000', | |
mobile: '+886 11111111' | |
}, | |
"address" : '天龍區' | |
} | |
var obj2 = { | |
"name" : { | |
fullName: 'Hello', | |
given: 'a name, b name, c name' | |
}, | |
"contact" : { | |
internal_phone: '0000000', | |
mobile: { | |
code: '+886', | |
number: { | |
} | |
} | |
}, | |
"address" : '天龍區' | |
} | |
function convertJSONAttributes(input){ | |
var result = {} | |
Object.keys(input).forEach(key => { | |
if(typeof input[key] === 'object'){ | |
input[key] = convertJSONAttributes(input[key]) | |
} | |
console.log("typeof input[key] === 'object'", typeof input[key] === 'object', key) | |
// console.log('result', result) | |
// console.log('key', key) | |
switch(key){ | |
// Level 1 | |
case 'name': | |
result[key] = input[key] | |
break; | |
case 'tel': | |
result['contact'] = input[key] | |
break; | |
// Level 2 | |
case 'full_name': | |
result['fullName'] = input[key] | |
break; | |
case 'phone': | |
result['internal_phone'] = input[key] | |
break; | |
case 'mobile': | |
// | |
var [code, number] = input[key].split(' ') | |
// | |
// var tmp = input[key].split(' ') | |
// var code = tmp[0] | |
// var number = tmp[1] | |
result['mobile'] = { | |
code, | |
number | |
} | |
break; | |
case 'given': | |
var tmp = [] | |
Object.keys(input[key]).forEach(_ => { | |
tmp.push(input[key][_]) | |
}) | |
result['given'] = tmp.join(',') | |
break; | |
default: | |
result[key] = input[key] | |
} | |
}) | |
return result | |
} | |
var r = convertJSONAttributes(obj) | |
console.log('result: ', r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment