Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

311
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!

about 4 years 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.

about 4 years 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 vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda