我想创建一个函数来在嵌套对象的任何级别切换字段值
function toggle(object, field) {
object[field] = !object[field];
}
但是如果我想像这样更改嵌套对象:
outer: {
inner: {
enable: true
}
}
我不能像 toggle(outer, 'inner.price')
或 toggle(outer.inner, 'price')
那样传递它。计算属性是否有一些技巧可以让我不解析参数字符串并递归地挖掘对象内部?
最佳答案
在 JS 中,您实际上可以通过使用它们的名称来访问属性,outer['inner']
与 outer.inner
相同,但您不需要在“编译”时知道属性名称。
您应该能够通过拆分字符串(例如 outer.inner.enable
)来通过递归找到您想要的属性。
let myObject = {
outer: {
inner: {
enable: true
}
}
};
const toggle = (object, path) => {
// get the name of the next property
let [prop, ...subProps] = path.split('.');
// check if the property to toggle is at this object
if (subProps.length == 0) {
// toggle said propertty
object[prop] = !object[prop];
} else {
// toggle property in child object
toggle(object[prop], subProps.join('.'));
}
}
console.log(myObject.outer.inner.enable); // true
toggle(myObject, 'outer.inner.enable');
console.log(myObject.outer.inner.enable); // false
关于javascript - 访问嵌套对象的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49177506/