Skip to content

Instantly share code, notes, and snippets.

@thachnuida
Last active October 12, 2016 04:05
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 thachnuida/c26507d0098cf10ceb66f7f0233126dc to your computer and use it in GitHub Desktop.
Save thachnuida/c26507d0098cf10ceb66f7f0233126dc to your computer and use it in GitHub Desktop.
Flat object
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