javascript access object property by key code example

Example 1: javascript object string property

// Also useful for dynamic strings, e.g. `thing-${variable}`
myObject['thing'] = true;

Example 2: 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}

Tags:

Php Example