我的Routine对象看起来像这样:
export class Routine {
id: string;
name: string;
exercises: RoutineExercise[];
}
Run Code Online (Sandbox Code Playgroud)
我的RoutineExercise对象看起来像这样:
export class RoutineExercise {
id: string;
presetKey: string;
preset: Preset;
}
Run Code Online (Sandbox Code Playgroud)
我需要将一个Routine对象转换为 JSON 对象,但我需要preset从每个对象中排除该对象RoutineExercise
所以我需要做这样的事情:
function replacer(key, value) {
if (key === "preset") { return undefined; }
}
const jsonString = JSON.stringify(routine, replacer);
console.log(JSON.parse(jsonString));
Run Code Online (Sandbox Code Playgroud)
但这并不排除我的预设。可能是因为preset键嵌套在exercise键中。
知道如何做到这一点吗?
您的替换功能不正确。每当您想要在 JSON 中包含键/值时,它都需要返回该值。您的代码使其仅返回undefined任何键/值。
所以使用这个:
function replacer(key, value) {
if (key !== "preset") { return value; }
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以测试值的类型:
function replacer(key, value) {
if (!(value instanceof Preset)) { return value; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1062 次 |
| 最近记录: |