[英]Convert keys and prototype methods to camelcase
I have a class instance whose constructor takes an object or a JSON string representing that object.我有一个类实例,其构造函数采用一个对象或一个表示该对象的 JSON 字符串。 *
*
Because that JSON comes from a remote source, I like to ensure that the properties all have a lowercase first letter.因为该 JSON 来自远程源,所以我喜欢确保所有属性的首字母都为小写。 However I've noticed that the method I'm using to do so (
Object.keys()
) ignores prototype methods.但是我注意到我使用的方法(
Object.keys()
)忽略了原型方法。 This makes sense after reading the documentation.阅读文档后,这是有道理的。 I considered
Object.getOwnPropertyNames()
instead but given that I'm not dealing with enumerable vs non-enumerable (as far as I know), that wouldn't make a difference.我考虑过
Object.getOwnPropertyNames()
但鉴于我没有处理可枚举与不可枚举(据我所知),这不会有什么区别。
Is there an alternative method I can use to lowercase the first letter of all keys and prototype methods?有没有一种替代方法可以用来小写所有键和原型方法的第一个字母?
Thanks.谢谢。 Demonstration below.
下面演示。
class B { constructor() { this.MyProperty = "Hello world!"; } MyMethod() {} } class A { constructor(b) { console.log(`MyMethod exists before lowercasing: ${!!b.MyMethod}`); b = Object.keys(b).reduce((copy,key) => ({...copy, [`${key[0].toLowerCase()}${key.slice(1)}`]: b[key]}),{}); console.log(`MyMethod exists after lowercasing: ${!!b.myMethod || !!b.MyMethod}`); console.log(`MyProperty has been lowercased: ${!!b.myProperty}`); } } let b = new B(); let a = new A(b);
* I've removed this for sake of brevity. * 为简洁起见,我已将其删除。
You could get the prototype from the instance using Object.getPrototypeOf(instance)
and then invoke Object.getOwnPropertyNames()
on the prototype to get the list of prototype methods.您可以使用
Object.getPrototypeOf(instance)
从实例中获取原型,然后在原型上调用Object.getOwnPropertyNames()
以获取原型方法列表。
Using Array.prototype.reduce()
you can combine the prototype methods as well as the keys of the object instance you have given into a single object and apply your lower-casing logic subsequently:使用
Array.prototype.reduce()
您可以将原型方法以及您提供的对象实例的键组合到一个对象中,然后应用您的小写逻辑:
class B { MyMethod() { return true } } class A { constructor(b) { console.log(`MyMethod exists before lowercasing: ${!!b.MyMethod}`); var proto = Object.getPrototypeOf(b); var comp = Object.getOwnPropertyNames(proto).reduce((obj, key) => {obj[key] = proto[key]; return obj}, {...b}) b = Object.keys(comp).reduce((copy,key) => ({...copy, [`${key[0].toLowerCase()}${key.slice(1)}`]: b[key]}),[]); console.log(`MyMethod exists after lowercasing: ${!!b.myMethod || !!b.MyMethod}`); } } let b = new B(); let a = new A(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.