LoginSignup
1

More than 5 years have passed since last update.

ドットつなぎのキーを使った連想配列を、深い階層の連想配列にする

Posted at

{"kinpatch.name":"Tetsuya","kinpatch.familyName":"Takeda"}

という連想配列と、

{"kinpatch":{"name":"Tetsuya","familyName":"Takeda"}}

というのを相互に変換できたら便利かも、と思ったのでやってみた。
(サンプルコードに他意はないです、たまたまテレビで出ていたので)

まずは 深キー→深階層 の変換。

mapToDeepMap.js
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));

次に、深階層→深キー の変換。

deepMapToMap.js
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));

がんばって書いたけど人が見るとどうなんだろう?
もっと上手に書けたり、そういうライブラリがあるよという人は教えてください。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1