获取JSON中的关键位置并修改

Getting key position in JSON and modify

我如何知道 JSON 中是否存在“xxx”键?我需要对这些 JSON 进行格式化:

let beforeOne = {
    "id": "123",
    "aDate": {
        "$date": "2022-06-24T00:00:00Z"
    }
}

let beforeTwo = {
    "id": "123",
    "firstDate": {
        "$date": "2022-06-24T00:00:00Z"
    },
    "day": {
         "today": {
             "$date": "2022-06-24T00:00:00Z"
         },
        "tomorrow": {
             "$date": "2022-06-24T00:00:00Z"
        }
    }
}

至:

let afterOne = {
    "id": "123",
    "aDate": new Date("2022-06-24T00:00:00Z")
}

let afterTwo = {
    "id": "123",
    "firstDate": new Date("2022-06-24T00:00:00Z"),
    "day": {
        "today": new Date("2022-06-24T00:00:00Z"),
        "tomorrow": new Date("2022-06-24T00:00:00Z")
    }
}

所以基本上,我需要找到存在“$date”的所有地方,将其删除并为 parentKey 提供 parentKey[=21= 的值].$date 与新的 Date() 构造函数。我怎么能那样做?提前致谢!

您可以为此使用递归函数。每次你看到一个对象有一个 $date 键,执行 new Date 转换和 return 这对调用者:

function transformDates(obj) {
    return Object(obj) !== obj ? obj // Primitive
         // When it has $date:
         : obj.hasOwnProperty("$date") ? new Date(obj.$date)
         // Recursion
         : Object.fromEntries(
               Object.entries(obj).map(([k, v]) => [k, transformDates(v)])
           );
}

let beforeOne = {"id": "123","aDate": {"$date": "2022-06-24T00:00:00Z"}}
console.log(transformDates(beforeOne));

let beforeTwo = {"id": "123","firstDate": {"$date": "2022-06-24T00:00:00Z"},"day": {"today": {"$date": "2022-06-24T00:00:00Z"},"tomorrow": {"$date": "2022-06-24T00:00:00Z"}}}
console.log(transformDates(beforeTwo));

请注意,Stack Snippets 在输出 Date 对象时会将它们转换回字符串。这不是您在浏览器的控制台中看到的,您在浏览器的控制台中可以真正获得 Date 对象的呈现。