0

我需要在javascript中获取/设置嵌套对象,我编写了以下setter,并且正在工作,我需要getter的帮助:假设我有以下对象,我想做类似的事情

var prop = get(object, ['complexObj', 'prop1']);
set(object, ['complexObj', 'prop1'], 'newValue');
var object = {
    complexObj: {
        'prop1': 'A'
        'prop2': 'B'},
    'prop3': 'C'
};

// helper function
var read = function(obj, prop) 
{
    if ((obj != null ? obj[prop] : void 0) == null) 
    {
        return;
    }
    return obj[prop];
};
// The following methods allow contextManager data to be accessed either via array of property name parts like ['complexObj', 'subObj', 'subProp1'] 
var get = function (props) {
    var current = properties;
    var val;
    for (var i = 0; i < props.length; i++) {
        if (val = read(current, props[i])) {
            current = val;
        } else {
            return '';
        }
    }
    return current;
};

如果有办法使用 Jquery/lodash 或其他库而不是在对象内部循环,我正在徘徊?我还需要一些关于二传手的帮助。

4

2 回答 2

0

尝试

var object = {
    complexObj: {
        'prop1': 'A',
        'prop2': 'B'
    },
    'prop3': 'C'
};

// helper function
var read = function(obj, prop) {
    return obj ? obj[prop] : undefined;
};
// The following methods allow contextManager data to be accessed either via array of property name parts like ['complexObj', 'subObj', 'subProp1'] 
var get = function (properties, props) {
    var current = properties;
    var val;
    for (var i = 0; i < props.length; i++) {
        if (val = read(current, props[i])) {
            current = val;
        } else {
            return undefined;
        }
    }
    return current;
};
console.log(get(object, ['complexObj', 'prop1']));
//set(object, ['complexObj', 'prop1'], 'newValue');
console.log(get(object, ['complexObj', 'prop1']));

演示:小提琴

get在定义之前我们调用的错误很少,您必须将objecttoget方法作为其第一个参数传递

于 2013-04-28T16:03:51.517 回答
0
// get a property
var get = function(obj, accessor) {
    for (var i = 0, len = accessor.length; i < len; i++) {
        if (!obj) return "";
        obj = obj[accessor[i]];
    }

    return obj;
};

// set a property
var set = function(obj, accessor, value) {
    for (var i = 0, len = accessor.length - 1; i < len; i++) {
        if (!obj) obj = {};
        obj = obj[accessor[i]] = obj[accessor[i]] || {};
    }

    obj[accessor[i]] = value;
};

// example
var object = {
    a: 2,
    b: {
        c: 1
    }
};

get(object, ["b", "c"]); // 1
set(object, ["d"], 3); // { a: 2, b: { c: 1 }, d: 3 }
set(object, ["e", "f"], 4); // { ..., e: { f: 4 } }

/*
object == {
    a: 2,
    b: {
        c: 1
    },
    d: 3,
    e: {
        f: 4
    }
}
*/

此代码在设置不存在的属性时自动创建新对象。

于 2013-04-28T16:07:35.093 回答