Set/Get Nested Object

by jacobwsmith

JavaScript

// ===============================================
// Get and set objects
// ===============================================
(function() {

	// Utility method to get and set objects that may or may not exist
	var objectifier = function(splits, create, context) {
		var result = context || window;
		for(var i = 0, s; result && (s = splits[i]); i++) {
			result = (s in result ? result[s] : (create ? result[s] = {} : undefined));
		}
		return result;
	};

	// Gets or sets an object
	jQuery.obj = function(name, value, create, context) {

		// JWS: Adding to account for arrays
		name = name.replace("[", ".");
		name = name.replace("]", ".");

		// Setter
		if(value !== undefined) {
			var splits = name.split("."), s = splits.pop(), result = objectifier(splits, true, context);
			return result && s ? (result[s] = value) : undefined;
		}
		// Getter
		else {
			return objectifier(name.split("."), create, context);
		}
	};

})();

// ===============================================
// TEST OBJ
// ===============================================
var obj = {
    sites: [{
        displayImpresions: 999,
        siteServed: true
    }]
}
var test1 = 'obj.sites[0].displayImpresions';
var test2 = 'obj.sites[0].siteServed';

// ===============================================
// Creates an input and binds
// ===============================================
var bindInput = function(bind){
	return $('<input>').attr('type', 'text').val(eval(bind)).change(function(){
		console.log(eval(test1));
        $.obj(bind, $(this).val());
        console.log(eval(test1));
	});
};
var bindCheckbox = function(bind){
	return $('<input>').attr('type', 'checkbox').prop('checked', eval(bind)).change(function(){
		console.log(eval(test2));
        $.obj(bind, $(this).prop('checked'));
        console.log(eval(test2));
	});
};

$('body').append(
    bindInput(test1),
    bindCheckbox(test2)
);