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

588
Views
Javascript: ¿cómo eliminar todas las propiedades anidadas nulas o indefinidas y los objetos vacíos?

Estoy buscando esencialmente "recortar" un objeto JSON a solo objetos y propiedades que tengan datos significativos no vacíos.

Necesito escribir una función performante que tome un objeto como este:

[Entrada de función]

 { "id": "123", "firstName": undefined "lastName": null "contactInfo": { "email": "notreal@somedomain.com", "contactInfo": { "address": { "streetAddress1": undefined, "state": null } } } }

[Salida de función]

 { "id": "123", "contactInfo": { "email": "notreal@somedomain.com" } }

Esto es lo que he probado:

 export function removeNullOrUndefinedProperties(obj: any): any { return Object.entries(obj) .filter(([_, v]) => v != null) .reduce((acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeNullOrUndefinedProperties(v) : v }), {}); } export function removeEmptyObjects(obj: any): any { for (const k in obj) { if (!obj[k] || typeof obj[k] !== 'object') { continue; // If null or not an object, skip to the next iteration } // The property is an object removeEmptyObjects(obj[k]); // <-- Make a recursive call on the nested object if (Object.keys(obj[k]).length === 0) { delete obj[k]; // The object had no properties, so delete that property } } return obj; }

Llamar a la función:

 removeEmptyObjects(removeNullOrUndefinedProperties(json));

Esta solución es lenta y no siempre funciona; específicamente, si pasa una matriz, devuelve índices numerados en la matriz que son datos inesperados. ¿Cómo escribo esta función de una manera correcta y eficiente?

about 4 years ago · Juan Pablo Isaza
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!