Traverse nested structures of JavaScript objects and arrays using string paths
P粉897881626
2023-08-15 21:01:19
<p>I have a data structure like this:</p>
<pre class="brush:php;toolbar:false;">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'
}
]
};</pre>
<p>I want to access the data using the following variables: </p>
<pre class="brush:php;toolbar:false;">var part1name = "part1.name";
var part2quantity = "part2.qty";
var part3name1 = "part3[0].name";</pre>
<p>part1name should be filled with the value of <code>someObject.part1.name</code>, which is "Part 1". The same goes for part2quantity, which is padded to 60. </p>
<p>Is there a way to achieve this using pure JavaScript or JQuery? </p>
This is now supported via lodash using
_.get(obj, property)
. See https://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 at http://jsfiddle.net/alnitak/hEsys/.
EDIT Some 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
.