Last active
August 29, 2015 13:56
-
-
Save luckydrq/9209205 to your computer and use it in GitHub Desktop.
post for `structs2 action`
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
/* Structs2的对象序列化 | |
* | |
* Example: | |
* {a:'a', b:[{c:'c'}, {d:'d'}]} | |
* | |
* => {'a':'a', 'b[0].c': 'c', 'b[1].d': 'd'} | |
* | |
*/ | |
function flattern(o) { | |
var result = {}; | |
function traverse(o, parent) { | |
parent = parent || ''; | |
var k, v, t, i, prefix; | |
if (isPrimative(o)) return o; | |
if (isObject(o)) { | |
prefix = parent ? parent + '.' : ''; | |
for (k in o) { | |
t = prefix + k; | |
v = o[k]; | |
if (isPrimative(v)) { | |
result[t] = v; | |
} else { | |
traverse(v, t); | |
} | |
} | |
} | |
if (isArray(o)) { | |
prefix = parent ? parent + '[$]' : '$'; | |
for (i = 0;i < o.length;i++) { | |
t = prefix.replace(/\$/, i); | |
v = o[i]; | |
if (isPrimative(v)) { | |
result[t] = v; | |
} else { | |
traverse(v, t); | |
} | |
} | |
} | |
} | |
traverse(o); | |
return result; | |
} | |
function isString(v) { | |
return 'string' == typeof v | |
} | |
function isBoolean(v) { | |
return 'boolean' == typeof v | |
} | |
function isNumber(v) { | |
return 'number' == typeof v | |
} | |
function isArray(v) { | |
return '[object Array]' == Object.prototype.toString.call(v) | |
} | |
function isObject(v) { | |
return '[object Object]' == Object.prototype.toString.call(v) | |
} | |
function isEmptyObject(v) { | |
if (isObject(v)) { | |
var f = false; | |
for (var p in v) { | |
if (v.hasOwnProperty(p)) { | |
f = true; | |
break; | |
} | |
} | |
return f; | |
} | |
return false; | |
} | |
function isPrimative(v) { | |
return isString(v) || isBoolean(v) || isNumber(v); | |
} |
ziyunfei
commented
Mar 28, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment