3 回答
TA贡献1828条经验 获得超6个赞
很少进行更正。
无论创建子对象,您都需要推进对象路径
要检查字符串类型,您需要使用typeof
var obj = {
keyOne: "foo",
keyTwo: {
test1: "baz",
test2: {
test21: ["bar"],
}
}
}
function setObjectProperty(obj, string, value) {
var path = string.split('.');
var currentObj = obj;
for (var i = 0; i < path.length - 1; i++) {
if (!currentObj[path[i]] || typeof currentObj[path[i]] === 'string') {
currentObj[path[i]] = {};
}
currentObj = currentObj[path[i]];
}
currentObj[path[path.length - 1]] = value;
};
setObjectProperty(obj, 'keyOne', 'new');
setObjectProperty(obj, 'keyOne.key.key2', 'newnew');
setObjectProperty(obj, 'keyTwo.test1', 'zzz');
console.log(obj);
TA贡献1875条经验 获得超5个赞
这个测试currentObj[path[i]] != "string"看起来很奇怪,我想你想用它typeof来代替。
在循环内部,您应该在每一步都前进,但仅在对象不存在时才创建它。
工作代码:
function setObjectProperty(obj, string, value) {
var path = string.split('.');
var currentObj = obj;
for (var i = 0; i < path.length - 1; i++) {
if (!currentObj[path[i]] || typeof currentObj[path[i]] == "string") {
currentObj[path[i]] = {};
}
currentObj = currentObj[path[i]];
}
currentObj[path[path.length - 1]] = value;
};
TA贡献1830条经验 获得超3个赞
这是你想要的?
const store = {
keyOne: "foo",
keyTwo: {
test1: "baz",
test2: {
test21: ["bar"],
}
}
}
function getKeys(key) {
return key.split(".").filter(k => k.length);
}
function assignProps(object, keys, value = null, root = null) {
root = root || object;
const key = keys.shift();
if (!key) return root;
object[key] = keys.length === 0 ? value : {};
assignProps(object[key], keys, value, root);
}
assignProps(store, getKeys("keyOne.foo.bar"), "baz");
assignProps(store, getKeys("keyTwo.test1.test2"), "value");
console.log(store);
添加回答
举报