Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

165
Vistas
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!

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.