Created
January 18, 2016 23:25
-
-
Save karenpeng/4f1e50b0fdf09cd2d44c to your computer and use it in GitHub Desktop.
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 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