通过字符串路径访问嵌套的JavaScript对象和Aray [英] Accessing nested JavaScript objects and arays by string path

查看:83
本文介绍了通过字符串路径访问嵌套的JavaScript对象和Aray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据结构:

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'
        }
    ]
};

我想使用这些变量访问数据:

And I would like to access the data using these variable :

var part1name = "part1.name";
var part2quantity = "part2.qty";
var part3name1 = "part3[0].name";

part1name应该用someObject.part1.name的值(即第1部分")填充.填充了60的part2quantity也是一样.

part1name should be filled with someObject.part1.name 's value, which is "Part 1". Same thing with part2quantity which filled with 60.

是否有纯JavaScript或JQuery来实现这一目标?

Is there anyway to achieve this with either pure javascript or JQuery?

推荐答案

我只是根据已经拥有的一些类似代码制作的,看来可行:

I just made this based on some similar code I already had, it appears to work:

Object.byString = function(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    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;
}

用法::

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

http://jsfiddle.net/alnitak/hEsys/

编辑有些人已经注意到,如果传递的字符串最左边的索引与对象内正确嵌套的条目不对应,则此代码将引发错误.这是一个有效的问题,但是IMHO最好在调用时使用try / catch块来解决,而不是让此函数默默地为无效索引返回undefined.

EDIT some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a try / catch block when calling, rather than having this function silently return undefined for an invalid index.

这篇关于通过字符串路径访问嵌套的JavaScript对象和Aray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆