Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
Obtener posición clave en JSON y modificar

¿Cómo puedo saber si en un JSON existe la clave "xxx"? Necesito que estos JSON estén formateados:

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

a:

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

Básicamente, necesito encontrar todos los lugares donde esté presente "$date", eliminarlo y darle a parentKey el valor de parentKey .$date con el nuevo constructor Date(). ¿Cómo podría hacer eso? ¡Gracias por adelantado!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede usar una función recursiva para esto. Cada vez que vea un objeto que tiene una clave $date , realice la new Date y devuélvala a la persona que llama:

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

Tenga en cuenta que Stack Snippets vuelve a convertir los objetos de fecha en cadenas cuando los genera. Esto no es lo que vería en la consola de un navegador, donde realmente obtiene una representación de los objetos Date.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!