javascript - JSON Stringify 忽略nesten 对象中的键?

标签 javascript json

我的例程对象如下所示:

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/

相关文章:

python - 类型错误 : b'1' is not JSON serializable

json - 访问jquery模板中的json文件

javascript - 我如何在 ejs 中使用脚本功能?

javascript - 检查 Canvas 段的透明度

javascript - 是否可以在 chrome 中从控制台加载外部 javascript 文件(来自 URL)?

python - 在 Python 中嵌套 JSON 库

javascript - 如何获取当前元素的计算样式

javascript - 在页面加载动画上制作 css 的正确方法是什么?

php - 如何从 MYSQL PHP 解码 JSON

javascript - 如何使用 React 中的 JSON 文件中的每个值生成组件?