我需要在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或其他库,而不是在对象内部循环,我是在游荡? 另外,我需要帮助设置者。
答案 0 :(得分: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']));
演示:Fiddle
我们在定义之前调用get
之类的错误很少,您必须将object
转换为get
方法作为其第一个参数
答案 1 :(得分: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
}
}
*/
此代码在设置不存在的属性时自动创建新对象。