Home > OS >  Getting key position in JSON and modify
Getting key position in JSON and modify

Time:06-03

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!

CodePudding user response:

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.

  • Related