react javascript dotnotation of array of string objects code example

Example 1: javascript dotify object

function dotify(obj) {
    const res = {};
    function recurse(obj, current) {
        for (const key in obj) {
            const value = obj[key];
            if(value != undefined) {
                const newKey = (current ? current + '.' + key : key);
                if (value && typeof value === 'object') {
                    recurse(value, newKey);
                } else {
                    res[newKey] = value;
                }
            }
        }
    }
    recurse(obj);
    return res;
}
dotify({'a':{'b1':{'c':1},'b2':{'c':1}}}) //{'a.b1.c':1,'a.b2.c':1}

Example 2: object notation string javascript\

function getValueFromNotation(obj: Object,is: string|any[], value: any = undefined) {
    
    if (typeof is == 'string')
      return getValueFromNotation(obj,is.split('.'), value);
    else if (is.length==1 && value!==undefined)
      return obj[is[0]] = value;
    else if (is.length==0)
      return obj;
    else
      return getValueFromNotation(obj[is[0]],is.slice(1), value);
  
}

Tags:

Java Example