我试图用字符串动态访问对象的属性。 例如: " .id.public" - > anyObject [" ID"] ["公共"]
问题 - 我不知道我有多少论点(例如" .id"或" .id.public"或" .id。 public.whatever"
我做了一点解决方法:
var currentSplit = anyObject;
var splitted = "id.public".split("\.");
splitted.forEach(function(s) { currentSplit = currentSplit[s]; });
当我现在尝试覆盖对象属性时,我将覆盖引用而不是对象属性。
currentSplit = "test";
我已尝试过类似anyObject["id.public"] = "test";
的内容,但它没有用。
答案 0 :(得分:2)
deep-get-set库可以满足您的需求:
function get (obj, path) {
var keys = path.split('.');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!obj || !hasOwnProperty.call(obj, key)) {
obj = undefined;
break;
}
obj = obj[key];
}
return obj;
}
function set (obj, path, value) {
var keys = path.split('.');
for (var i = 0; i < keys.length - 1; i++) {
var key = keys[i];
if (deep.p && !hasOwnProperty.call(obj, key)) obj[key] = {};
obj = obj[key];
}
obj[keys[i]] = value;
return value;
}
答案 1 :(得分:1)
另一种设定价值的方法
function setVal(obj, path, val){
var paths = path.split('.'),
curProp = obj;
for(var i=0;i<paths.length-1;i++){
curProp = curProp[paths[i]];
}
curProp[paths[i]] = val;
}
并像
一样使用它setVal(anyObj, "id.public", 'newValue');
答案 2 :(得分:0)
如果没有像这样的小代码的帮助,你就无法做到这一点:
var mapToProperty = function(obj, path, value) {
if (!path) return obj;
var parts = path.split("."),
p = parts[0],
v = (typeof obj[p] === "function") ? obj[p](value) : (parts.length !==1 || !value) ? obj[p] : (obj[p] = value), value ;
if (parts.length == 1) return v;
return mapToProperty(v, parts.slice(1).join("."), value);
}
// use it like this
var myvalue = mapToProperty(myObj, "address.street")
// you can map into your objects as far as you want. obj1.obj2.obj3.prop
// you can set as well :-)
mapToProperty(myObj, "address.street", "This is great!")