我的例程对象如下所示:
export class Routine {
id: string;
name: string;
exercises: RoutineExercise[];
}
我的 RoutineExercise 对象如下所示:
export class RoutineExercise {
id: string;
presetKey: string;
preset: Preset;
}
我需要将 Routine 对象转换为 JSON 对象,但我需要从每个 RoutineExercise
中排除 preset
对象
所以我需要做这样的事情:
function replacer(key, value) {
if (key === "preset") {return undefined; }
}
const jsonString = JSON.stringify(routine, replacer);
console.log(JSON.parse(jsonString));
但这并不排除我的预设。可能是因为 preset
键嵌套在 exercise
键中。
知道如何做到这一点吗?
最佳答案
您的替换函数不正确。每当您想要在 JSON 中包含键/值时,它都需要返回该值。您的代码使其仅返回 undefined
无论键/值是什么。
所以使用这个:
function replacer(key, value) {
if (key !== "preset") { return value; }
}
或者,您可以测试值的类型:
function replacer(key, value) {
if (!(value instanceof Preset)) { return value; }
}
关于javascript - JSON Stringify 忽略nesten 对象中的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55314923/