I have a data structure like this:
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' } ] };
I want to access the data using the following variables:
var part1name = "part1.name"; var part2quantity = "part2.qty"; var part3name1 = "part3[0].name";
part1name should be filled with the value of someObject.part1.name
, which is "Part 1". The same goes for part2quantity, which is padded to 60.
Is there a way to achieve this using pure JavaScript or JQuery?
This is now supported via lodash using
_.get(obj, property)
. Seehttps://lodash.com/docs#getExample from documentation:
I just created this based on some similar code I already had and it seems to work:
usage:
View a working example athttp://jsfiddle.net/alnitak/hEsys/.
EDITSome people have noticed that this code will throw an error if passed a string where the leftmost index does not correspond to a properly nested entry in the object. This is a valid concern, but I think it's better handled using a
try/catch
block when called, rather than having this function silently returnundefined
.