Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

javascript - 使用字符串键访问嵌套的JavaScript对象(Accessing nested JavaScript objects with string key)

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 should be filled with someObject.part1.name 's value, which is "Part 1".

(part1name应该用someObject.part1.name的值填充,即“ Part 1”。)

Same thing with part2quantity which filled with 60.

(part2quantity填充60。)

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

(无论如何,可以使用纯JavaScript或JQuery来实现这一点?)

  ask by Komaruloh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Usage::

(用法::)

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

See a working demo at http://jsfiddle.net/alnitak/hEsys/

(在http://jsfiddle.net/alnitak/hEsys/上查看有效的演示)

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.

(这是一个有效的问题,但是IMHO最好在调用时使用try / catch块来解决,而不是让此函数为无效索引默默地返回undefined 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...