孅いエンジニアブログ

オブジェクトのnullを全てundefinedにする処理

実はこのブログ、microCMSとやらで記事書いてます。

このCMS、返ってくる値が無い時にundefinedだったりnullだったりします。

nullとundefinedの判定がちょっとめんどくさかったので、null全部undefinedにしちゃおうぜって思ってnullを全部undefinedにする処理を作ってみました。

// nullを全てundefinedに変換
export const nullToUndefined = <T>(object: T): T => {
	for (const value in object) {
		// nullの場合はundefinedにする
		if (object[value] === null) {
			object[value] = undefined as Extract<keyof T, undefined>;

			continue;
		}

		// 配列の場合はfor文で再起的に回す
		if (Array.isArray(object[value])) {
			const array = object[value] as Extract<keyof T, unknown[]>;
			for (let i = 0; i < array.length; i++) {
				array[i] = nullToUndefined(array[i]);
			}

			continue;
		}

		// オブジェクトの場合も再起的に実行
		if (typeof object[value] === "object") {
			object[value] = nullToUndefined(object[value]);

			continue;
		}
	}

	return object;
};

値がnullであればundefinedを返す。

値が配列の場合は再帰的に回す。

オブジェクト場合はまるごともう1回処理に渡す。

という感じの処理でやっています。

自分の中では頑張った方な処理ですが、間違ってたら教えてください。