转换深嵌套类对象到普通对象,同时保留方法?



有一个类对象(与更多的类对象深度嵌套),我想将其转换为普通的Object类型,同时保留方法(getter, setter等)。

class A {
id = "";
data = {
sync: {}
};
}
class SyncService {
syncResultServiceA = {
ToSync: 0,
Synced: 0,
SyncErrors: [],
};
syncResultServiceB = {
ToSync: 0,
Synced: 0,
Errors: [],
};
}
const a = new A();
a.data.sync = new SyncService();
console.log(a.data.sync.constructor.name) // "SyncService"

我尝试了一堆解决方案:{...obj}不会为嵌套类对象工作,JSON.stringify() + parse()会删除自定义方法等。

试试这个:

class A {
constructor() {
this.id = '';
this.data = {
sync: {},
};
}
}
class SyncService {
constructor() {
this.syncResultServiceA = {
ToSync: 0,
Synced: 0,
SyncErrors: [],
};
this.syncResultServiceB = {
ToSync: 0,
Synced: 0,
Errors: [],
};
}
}
const a = new A();
a.data.sync = new SyncService();
console.log(a.data.sync.constructor.name) // "SyncService"
const b = convertToPlainObject(a);
console.log(b.data.sync.constructor.name);
function convertToPlainObject(cls) {
const copy = {
...cls
};
for (const [k, v] of Object.entries(copy)) {
if (typeof v === 'object') {
copy[k] = convertToPlainObject(v);
}
}
return copy;
}

您可以使用递归遍历所有嵌套对象并转换它们。下面是一个例子:

class A {
id = "";
data = {
sync: {}
};
}
class SyncService {
syncResultServiceA = {
ToSync: 0,
Synced: 0,
SyncErrors: [],
};
syncResultServiceB = {
ToSync: 0,
Synced: 0,
Errors: [],
};
}
const a = new A();
a.data.sync = new SyncService();
console.log(a.data.sync.constructor.name) // "SyncService"
const toPlain = (o) => {
if (typeof o === 'object' && !Array.isArray(o)) {
return {...Object.keys(o).reduce((a, c) => (a[c] = toPlain(o[c]), a), {})};
}
return o;
}
const plain = toPlain(a);
console.log(plain.data.sync.constructor.name) // "Object"

最新更新