Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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;
- }
Add Comment
Please, Sign In to add comment