Last active
October 12, 2016 04:05
-
-
Save thachnuida/c26507d0098cf10ceb66f7f0233126dc to your computer and use it in GitHub Desktop.
Flat object
This file contains hidden or 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 a = { | |
b: { | |
c: { | |
d: { | |
e: 'text 1' | |
} | |
} | |
}, | |
f: 'text' | |
}; | |
function flatKeyValue(obj, key) { | |
if (typeof (obj[key]) !== 'object') { | |
return { | |
key: key, | |
value: obj[key] | |
}; | |
} | |
for (var k in obj[key]) { | |
var flatKV = flatKeyValue(obj[key], k); | |
// Only run on first key, because we return here | |
return { | |
key: key + '.' + flatKV.key, | |
value: flatKV.value | |
} | |
} | |
} | |
function parse(data) { | |
var result = {}; | |
var flatKV; | |
for (var key in data) { | |
flatKV = flatKeyValue(data, key); | |
result[flatKV.key] = flatKV.value; | |
} | |
return result; | |
} | |
console.log(parse(a)); | |
/** Result | |
result = { | |
'b.c.d.e': 'text1', | |
'f': 'text' | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment