Last active
August 29, 2015 14:04
-
-
Save south-str/df53898cb880f4f0bcd8 to your computer and use it in GitHub Desktop.
Objectから値またはキーの一覧を取得する。
This file contains hidden or 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 a = { | |
"a":{ | |
"aa":0 | |
, "ab":1 | |
, "ac":2 | |
, "ad":3 | |
, "exa":{ | |
"exaa":"asdf" | |
} | |
}, | |
"b":{ | |
",exb":{ | |
//"exbb":true | |
} | |
, "aa":10 | |
, "ab":11 | |
, "ac":12 | |
, "ad":13 | |
}, | |
"c":{ | |
"aa":20 | |
, "ab":21 | |
, "exc":['a','b',2] | |
, "ac":22 | |
, "ad":23 | |
}, | |
"d":{ | |
"aa":30 | |
, "ab":31 | |
, "ac":32 | |
, "exd":false | |
, "ad":33 | |
, "exdd,":',,,' | |
} | |
}; | |
//Object内部のvalueを再帰的に取得する | |
function objValue(obj){ | |
return typeof obj == "object" ? Object.keys(obj).map(function(key){ | |
return objValue(obj[key]); | |
}) : obj; | |
} | |
//Object内部のkeyを再帰的に取得する | |
function objKey(obj){ | |
if(typeof obj == "object"){ | |
return Object.keys(obj).map(function(elem){ | |
return typeof obj[elem] == "object" ? [elem, objKey(obj[elem])] : elem; | |
}); | |
}else{ | |
return obj; | |
} | |
} | |
//n次元配列を1次元配列に置き換える | |
function toOneD(array){ | |
var result = []; | |
if(Array.isArray(array)){ | |
array.forEach(function getElem(x){ | |
Array.isArray(x) ? x.forEach(getElem) : result.push(x); | |
}); | |
} | |
return result; | |
} | |
var log = function(x){console.log(x);}; | |
log(toOneD(objValue(a))); | |
log(toOneD(objKey(a))); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment