Skip to content

Instantly share code, notes, and snippets.

@Laslo89
Last active February 24, 2020 19:36
Show Gist options
  • Save Laslo89/adce0310bfcf3c0e66a49cac129ace19 to your computer and use it in GitHub Desktop.
Save Laslo89/adce0310bfcf3c0e66a49cac129ace19 to your computer and use it in GitHub Desktop.
some helpful helper functions regarding object manipulation, arrays and so on
// convert plain object to dot notation
// For example the following object:
/*
const obj = {
app: {
lang: {
menu: {
welcome: "welcome",
label: "label"
},
sensor: "sensor",
sensors: {
headline: "headline",
text: "text"
}
}
}
}
*/
// converts to:
/*
[
"app.lang.menu.welcome",
"app.lang.menu.label",
"app.lang.menu.sensor",
"app.lang.menu.sensors.headline",
"app.lang.menu.sensors.text"
]
*/
// IE11 compatiple version
function ObjectToDotNotation(obj, dots, dot) {
if(typeof obj === 'string') return obj;
if(!dots) dots = [];
if(!dot) dot = "";
for(var key in obj) {
var val = obj[key];
var isObject = val != null && typeof val === 'object' && Array.isArray(val) === false;
if (isObject) {
dot += dot ? '.' + key : key;
ObjectToDotNotation(val, dots, dot);
} else if (typeof val === 'string') {
dots.push(dot + '.' + key);
}
}
return dots;
}
// ES6 version, not compatible with older browsers
function ObjectToDotNotation(obj, dots = [], dot = "") {
if (typeof obj === 'string') {
return obj;
}
Object.keys(obj).forEach((key) => {
let val = obj[key];
if (val != null && typeof val === 'object' && Array.isArray(val) === false) {
dot += dot ? `.${key}` : key
ObjectToDotNotation(val, dots, dot);
} else if (typeof val === 'string') {
dots.push(`${dot}.${key}`);
}
});
return dots;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment