Skip to content

Instantly share code, notes, and snippets.

@luckydrq
Last active August 29, 2015 13:56
Show Gist options
  • Save luckydrq/9209205 to your computer and use it in GitHub Desktop.
Save luckydrq/9209205 to your computer and use it in GitHub Desktop.
post for `structs2 action`
/* 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
Copy link

function flatten(obj) {
  var flattenObj = {};
  walker(obj);
  return flattenObj;

  function walker(value, path) {
    path = path || "" //第一次调用walker, path赋一个空字符串
    if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null) { //如果发现属性值是原始值, 就把path和属性值放进flattenObj对象里,不再进行递归
      flattenObj[path] = value
    } else { //如果发现属性值是个对象
      for (var i in value) { //就遍历这个对象的所有属性
        var nextPath //计算出传给下次walker调用的path
        if (path === "") { //如果是第一级属性,path就是属性名
          nextPath = i
        } else if (({}).toString.call(value) === "[object Array]") { //如果不是第一级属性,且属性值是数组,则用"path + [属性名]"作为下一级的path
          nextPath = path + "[" + i + "]"
        } else {
          nextPath = path + "." + i //如果不是第一级属性,且属性值是个普通对象,则用 "path + .属性名" 作为下一级的path
        }
        walker(value[i], nextPath) //递归
      }
    }
  }
}

var obj = {
  foo: {
    foo2: {
      foo3: 1,
      foo4: 2
    }
  },
  bar: [1, 2, 3],
  baz: "1"
};

flatten(obj)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment