Last active
September 23, 2016 09:35
-
-
Save hiyangguo/7de5b93334a701a7c969b502d2d14e33 to your computer and use it in GitHub Desktop.
parse {a:{b:1}} to {a.b:1}
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
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