Function: Get by dot notation

Extend object via dot notation query

by imcrthy

JavaScript

console.clear();

function get_by_dot(obj, str) { 
    return str.split(".").reduce(function(o, x) {
        return o[x]
    }, obj);
}

var User = {
    name: 'Andy',
    age: 20,
    sex: 'male',
    alive: true,
    education: {
        undergraduate: 'campbell university',
        graduate: 'webster',
        high_school: 'woodbury high',
        specialties: {
            business: [ 'one', 'two', 'three' ],
            accounting: [ 'advanced', 'quickbooks' ]
        }
    },
    skills: [ 'php', 'jquery' ]
}

// Get specialties branch
//var specialties = get_by_dot( User, 'education.specialties' );

// Add new property to specialties
//specialties.whatever = { 'asda': 'ass', 'asdas': 'asd' };
                        
// Main object should be reflected
// console.log( User.education.specialties.whatever );                     





// Get specialties branch
var specialties = User.education.specialties;

// Add new property to specialties
specialties.whatever = { 'asda': 'ass', 'asdas': 'asd' };

// Main object should be reflected
console.log( User.education.specialties.whatever );


console.log('\b');


// or just do this:

// Add new property to specialties
User.education.specialties.whatever = { 'asda': 'ass', 'asdas': 'asd' };

// Main object should be reflected
console.log( User.education.specialties.whatever );