Created
November 22, 2013 07:45
-
-
Save yogendra/7596317 to your computer and use it in GitHub Desktop.
Nested property getter and setter methods #Javascript #Utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Object.prototype.setNested = function(s, v) { | |
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties | |
s = s.replace(/^\./, ''); // strip a leading dot | |
var a = s.split('.'); | |
o = this; | |
while (a.length) { | |
var n = a.shift(); | |
if(a.length == 0){ | |
o[n]=v; | |
return; | |
}else if (n in o) { | |
o = o[n]; | |
} else { | |
return; | |
} | |
} | |
} | |
Object.prototype.getNested = function(s){ | |
var o = this; | |
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties | |
s = s.replace(/^\./, ''); // strip a leading dot | |
var a = s.split('.'); | |
while (a.length) { | |
var n = a.shift(); | |
if (n in o) { | |
o = o[n]; | |
} else { | |
return; | |
} | |
} | |
return o; | |
} | |
// Example | |
var someObject = { | |
'part1' : { | |
'name': 'Part 1', | |
'size': '20', | |
'qty' : '50' | |
}, | |
'part2' : { | |
'name': 'Part 2', | |
'size': '15', | |
'qty' : '60' | |
}, | |
'part3' : [ | |
{ | |
'name': 'Part 3A', | |
'size': '10', | |
'qty' : '20' | |
}, { | |
'name': 'Part 3B', | |
'size': '5', | |
'qty' : '20' | |
}, { | |
'name': 'Part 3C', | |
'size': '7.5', | |
'qty' : '20' | |
} | |
] | |
}; | |
console.log(someObject.getNested( 'part1.name')); | |
console.log(someObject.getNested( 'part2.qty')); | |
console.log(someObject.getNested( 'part3[0].name')); | |
someObject.setNested( 'part3[0].name', "Changed"); | |
console.log(someObject.getNested( 'part3[0].name')); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment