Make object serializable (New object)

Code Snippets 4 U

We will not be touching the old object (keeping the descriptors intact). Instead we will create new object, which will be serializable

makeObjectSerializable = <T>(obj: any): T => {
	if (!obj || typeof obj !== 'object') {
		return obj;
	}
	const objReturn = Array.isArray(obj) ? [] : ({} as any);
	const props = Object.keys(obj);
	for (const prop of props) {
		if (typeof obj[prop] !== 'function') {
			if (!Array.isArray(obj) && typeof obj[prop] === 'object') {
				objReturn[prop] = makeObjectSerializable(obj[prop]);
			} else if (Array.isArray(obj)) {
				objReturn[Number(prop)] = makeObjectSerializable(obj[Number(prop)]);
			} else {
				objReturn[prop] = obj[prop];
			}
		}
	}
	return objReturn;
};

Leave a Reply

Your email address will not be published. Required fields are marked *

fifty seven − = forty eight