Traverse nested structures of JavaScript objects and arrays using string paths
P粉897881626
P粉897881626 2023-08-15 21:01:19
0
2
382
<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>
P粉897881626
P粉897881626

reply all(2)
P粉720716934

This is now supported via lodash using _.get(obj, property). See https://lodash.com/docs#get

Example from documentation:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// → 3

_.get(object, ['a', '0', 'b', 'c']);
// → 3

_.get(object, 'a.b.c', 'default');
// → 'default'
P粉733166744

I just created this based on some similar code I already had and it seems to work:

Object.byString = function(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.'); // 将索引转换为属性
    s = s.replace(/^\./, '');           // 去掉前导点
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
}

usage:

Object.byString(someObj, 'part3[0].name');

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 return undefined.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!