Skip to content

Instantly share code, notes, and snippets.

@hiyangguo
Last active September 23, 2016 09:35
Show Gist options
  • Save hiyangguo/7de5b93334a701a7c969b502d2d14e33 to your computer and use it in GitHub Desktop.
Save hiyangguo/7de5b93334a701a7c969b502d2d14e33 to your computer and use it in GitHub Desktop.
parse {a:{b:1}} to {a.b:1}
var test = {
id: 1,
user: {
role: [1, 2, 3, 4],
userGroup: {
id: 1
},
name: {
first: "foo",
last: "bar"
}
}
};
function parseTreeObjToLine(origin) {
var o = {};
return (function convert(obj, keyPath) {
if (Object.prototype.toString.call(obj).slice(8, -1) !== 'Object') {
o[keyPath] = obj;
return;
}
Object.keys(obj).forEach(function(key) {
keyPath = keyPath === '' || (~Object.keys(origin).indexOf(key) && keyPath.split('.').length) ? key : [keyPath, key].join('.');
convert(obj[key], keyPath);
});
return o;
})(origin, '');
}
console.log(parseTreeObjToLine(test));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment