Last active
July 16, 2018 07:16
-
-
Save xincici/bc33d71536f203589a4a to your computer and use it in GitHub Desktop.
flat an object
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 person = { | |
name : { | |
first : 'ye', | |
last : 'lin' | |
}, | |
age : 28, | |
gender : 'male', | |
birth : { | |
year : 1987, | |
month : 6, | |
date : 15 | |
}, | |
education : { | |
college : 'zzu', | |
graduate : 'bupt', | |
middle : { | |
junior : 'ny26', | |
senior : 'nyyz' | |
} | |
} | |
} | |
var flat = function(obj){ | |
var result = {}; | |
function fn(obj, prev) { | |
var key, val; | |
for(key in obj){ | |
if(obj.hasOwnProperty(key)){ | |
val = obj[key]; | |
if(typeof val === 'object'){ | |
if(prev){ | |
fn(val, prev + '.' + key); | |
}else{ | |
fn(val, key); | |
} | |
}else{ | |
if(prev){ | |
result[prev + '.' + key] = val; | |
}else{ | |
result[key] = val; | |
} | |
} | |
} | |
} | |
} | |
fn(obj); | |
return result; | |
} | |
console.log(flat(person)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment