オブジェクトからJSON文字列を作成するには、JSON.stringifyを使います。
JSON.stringifyは、target、replacer、spaceの引数があります。
replacer関数内のif文の条件typeofが無い場合は、undefinedになってしまいます。
const target = {a: "apple", b: "banana", l: "lemon"};
function replacerNG(prop, value) {
if (value !== "banana") {
return
}
return value;
}
console.log(JSON.stringify(target, replacerNG));
> undefined
replacer関数内のif文の条件typeofがある場合は、条件にあった「banana」が変換されています。
const target = {a: "apple", b: "banana", l: "lemon"};
function replacerOK(prop, value) {
if (typeof value === "string" && value !== "banana") {
return
}
return value;
}
console.log(JSON.stringify(target, replacerOK));
> {"b":"banana"}
これは、replace関数の挙動に関係があります。
オブジェクトのプロパティごとに繰り返し、replacer関数が呼び出されます。
1回目の呼び出しでは、key="", value={a: "apple", b: "banana", l: "lemon"}が渡されます。
2回目の呼び出しでは、key="a"、value="apple"が渡され、3回目の呼び出しでは、key="b"、value="banana"、4回目の呼び出しでは、key="l"、value="lemon"が渡れます。
つまり、1回目の呼び出しでは、value={a: "apple"、b: "banana"、l: "lemon"}と、"banana"の比較が行われ、条件式の結果がtrueとなり、undefinedが戻されることになります。
このような挙動を避けるために、if文の条件にtypeofを含める必要があります。