Created
December 10, 2013 16:46
-
-
Save kanemu/7893836 to your computer and use it in GitHub Desktop.
ドットつなぎのキーを使った連想配列を、深い階層の連想配列にする ref: http://qiita.com/kanemu@github/items/8d103877ddcefd0c0ebf
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
function deepMapToMap(map,tmpMap,suffixkey){ | |
if(suffixkey==null) suffixkey = ''; | |
if(tmpMap==null) tmpMap = {}; | |
for(var key in map){ | |
if(map[key].constructor.name==='Object'){ | |
deepMapToMap(map[key],tmpMap,suffixkey+key+'.'); | |
}else{ | |
tmpMap[suffixkey+key] = map[key]; | |
} | |
} | |
return tmpMap; | |
} | |
var map = { | |
"kinpatch": { | |
"name": "Tetsuya", | |
"familyName": "Takeda" | |
}, | |
"date": "2013-12-10" | |
}; | |
var newMap = deepMapToMap(map); | |
console.log(JSON.stringify(newMap, undefined, 2)); |
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
function makeMap(keyAry,value,tmpMap){ | |
var key = keyAry.shift(); | |
if(tmpMap[key]==null){ | |
tmpMap[key] = (keyAry.length)? makeMap(keyAry,value,{}): value; | |
}else{ | |
if(tmpMap[key].constructor.name=='Object'){ | |
tmpMap[key] = makeMap(keyAry,value,tmpMap[key]); | |
} | |
} | |
return tmpMap; | |
} | |
function mapToDeepMap(map){ | |
var newMap = {}; | |
for(var key in map){ | |
makeMap(key.split('.'),map[key],newMap); | |
}; | |
return newMap; | |
} | |
var sampleMap = { | |
"kinpatch.name":"Tetsuya", | |
"kinpatch.familyName":"Takeda", | |
"date":"2013-12-10" | |
}; | |
var newMap = mapToDeepMap(sampleMap); | |
console.log(JSON.stringify(newMap, undefined, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment