Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting key position in JSON and modify

How can I know if in a JSON exists "xxx" key? I need these JSONs to be formatted:

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"
        }
    }
}

to:

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")
    }
}

So basically, I need to find everywhere where "$date" is present, remove it and give the parentKey the value from parentKey.$date with the new Date() constructor. How could I do that? Thanks in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a recursive function for this. Each time you see an object that has a $date key, perform the new Date transformation and return this to the caller:

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));

Note that Stack Snippets converts Date objects back to string when outputting them. This is not what you would see in a browser’s console, where you really get a rendering of Date objects.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading