P粉7207169342023-08-16 19:39:27
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粉7331667442023-08-16 14:08:25
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
.