How to set object property (of object property of..) given its string name in JavaScript?

后端 未结 14 2098
离开以前
离开以前 2020-11-22 02:20

Suppose we are only given

var obj = {};
var propName = \"foo.bar.foobar\";

How can we set the prop

14条回答
  •  我寻月下人不归
    2020-11-22 02:57

    Object.getPath = 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.setPath = function(o, p, v) {
        var a = p.split('.');
        var o = o;
        for (var i = 0; i < a.length - 1; i++) {
            if (a[i].indexOf('[') === -1) {
                var n = a[i];
                if (n in o) {
                    o = o[n];
                } else {
                    o[n] = {};
                    o = o[n];
                }
            } else {
                // Not totaly optimised
                var ix = a[i].match(/\[.*?\]/g)[0];
                var n = a[i].replace(ix, '');
                o = o[n][ix.substr(1,ix.length-2)]
            }
        }
    
        if (a[a.length - 1].indexOf('[') === -1) {
            o[a[a.length - 1]] = v;
        } else {
            var ix = a[a.length - 1].match(/\[.*?\]/g)[0];
            var n = a[a.length - 1].replace(ix, '');
            o[n][ix.substr(1,ix.length-2)] = v;
        }
    };
    

提交回复
热议问题