Skip to content

Instantly share code, notes, and snippets.

@kanemu
Created December 10, 2013 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanemu/7893836 to your computer and use it in GitHub Desktop.
Save kanemu/7893836 to your computer and use it in GitHub Desktop.
ドットつなぎのキーを使った連想配列を、深い階層の連想配列にする ref: http://qiita.com/kanemu@github/items/8d103877ddcefd0c0ebf
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));
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