Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Created January 18, 2016 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karenpeng/4f1e50b0fdf09cd2d44c to your computer and use it in GitHub Desktop.
Save karenpeng/4f1e50b0fdf09cd2d44c to your computer and use it in GitHub Desktop.
var input = {
a: { b : { c : 1 }, f : {g : 2}},
c: { d : 2 },
e: null,
f: {g: null} //这个应该输出什么
//是NULL还是一个变量啊?不知道啊那个人应该不是用javasscript的我们就当null好了
}
var output = {'a.b.c': 1, 'a.f.g': 2, 'c.d': 2, 'e': null, 'f.g': null}
function convert(obj){
var bigObj = {}
for(var key in obj){
helper(bigObj, obj, '')
}
return bigObj
}
function helper(bigObj, obj, str){
for(var key in obj){
var copy = str
copy += ('.' + key)
if(Object.prototype.toString.call(obj[key]) === '[object Object]'){
helper(bigObj, obj[key], copy);
}else{
bigObj[copy.slice(1)] = obj[key];
}
}
}
console.log(convert(input))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment