Traverse nested structures of JavaScript objects and arrays using string paths
P粉897881626
P粉897881626 2023-08-15 21:01:19
0
2
341

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?

P粉897881626
P粉897881626

reply all (2)
P粉720716934

This is now supported via lodash using_.get(obj, property). Seehttps://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 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 atry/catchblock when called, rather than having this function silently returnundefined.

      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!