在 JS 中,如何访问任何给定对象的给定 属性 路径?
In JS, how do I access a given property path of any given object?
为了使事情更清楚,这里有一个例子。我试图将所有内容都剥离到骨头上,只保留相关细节。这是一个带有一些属性和子属性的虚拟 class Person
:
class Person {
height = 100;
hat = {size: 4};
}
现在,我还有一些其他的class,其目的是修改Person
的一些(sub)*属性:
class PersonModifier {
constructor(propertyPath, value) {
this.propertyPath = propertyPath; // this is the part I'm a bit lost on
this.value = value; // a numeric value just to demonstrate how this class would work
}
actUpon(person) { // modifies a quantitative attribute of Person by a given amount
person.(this.propertyPath) += value;
}
}
我知道 actUpon
方法中的唯一一行代码在语法上不起作用,我希望我明白我正在尝试做什么。我想它类似于 Person.prototype.whatever
但我想将它用于属性而不是方法。
下面是上述class实例的一个例子,其目的是将一个人的帽子尺寸减小2:
let hatShrinker = new PersonModifier(.hat.size, -2);
同样,这显然在语法上不起作用,所以这是我的问题:
如何存储和使用 属性 路径(任意深度),以便我可以访问和写入任何对象的此类属性?假设我事先知道对象属于什么classes(在这个例子中,Person
)。
注意: 任何不涉及字符串的解决方案都是首选,因为字符串不受某些重要的 IDE 功能的影响,例如重构和基于建议的功能动态类型
我认为您可能受困于某种字符串。在此示例中,我使用一个字符串数组深入对象路径并改变最终对象的最终键。
class PersonModifier {
constructor(propertyPath, value) {
this.propertyPath = propertyPath;
this.value = value;
}
actUpon(person) {
const path = [...this.propertyPath];
const prop = path.pop();
const obj = path.reduce((acc, el) => {
return acc[el];
}, person);
obj[prop] += this.value;
}
}
const hatShrinker = new PersonModifier(["hat", "size"], -2);
const person = {
hat: {
size: 4
}
};
hatShrinker.actUpon(person);
console.log(person);
为了使事情更清楚,这里有一个例子。我试图将所有内容都剥离到骨头上,只保留相关细节。这是一个带有一些属性和子属性的虚拟 class Person
:
class Person {
height = 100;
hat = {size: 4};
}
现在,我还有一些其他的class,其目的是修改Person
的一些(sub)*属性:
class PersonModifier {
constructor(propertyPath, value) {
this.propertyPath = propertyPath; // this is the part I'm a bit lost on
this.value = value; // a numeric value just to demonstrate how this class would work
}
actUpon(person) { // modifies a quantitative attribute of Person by a given amount
person.(this.propertyPath) += value;
}
}
我知道 actUpon
方法中的唯一一行代码在语法上不起作用,我希望我明白我正在尝试做什么。我想它类似于 Person.prototype.whatever
但我想将它用于属性而不是方法。
下面是上述class实例的一个例子,其目的是将一个人的帽子尺寸减小2:
let hatShrinker = new PersonModifier(.hat.size, -2);
同样,这显然在语法上不起作用,所以这是我的问题:
如何存储和使用 属性 路径(任意深度),以便我可以访问和写入任何对象的此类属性?假设我事先知道对象属于什么classes(在这个例子中,Person
)。
注意: 任何不涉及字符串的解决方案都是首选,因为字符串不受某些重要的 IDE 功能的影响,例如重构和基于建议的功能动态类型
我认为您可能受困于某种字符串。在此示例中,我使用一个字符串数组深入对象路径并改变最终对象的最终键。
class PersonModifier {
constructor(propertyPath, value) {
this.propertyPath = propertyPath;
this.value = value;
}
actUpon(person) {
const path = [...this.propertyPath];
const prop = path.pop();
const obj = path.reduce((acc, el) => {
return acc[el];
}, person);
obj[prop] += this.value;
}
}
const hatShrinker = new PersonModifier(["hat", "size"], -2);
const person = {
hat: {
size: 4
}
};
hatShrinker.actUpon(person);
console.log(person);