Skip to content

Instantly share code, notes, and snippets.

@xincici
Last active July 16, 2018 07:16
Show Gist options
  • Save xincici/bc33d71536f203589a4a to your computer and use it in GitHub Desktop.
Save xincici/bc33d71536f203589a4a to your computer and use it in GitHub Desktop.
flat an object
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