¿Cómo puedo modificar el código de muestra de soplado para no solo buscar claves vacías sino también nulas e indefinidas?
Lo intenté
(obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined)pero eso lo rompió y no funcionó en absoluto, así que si uso cualquiera de las dos condiciones, funcionará, pero no cuando esté todo junto. Entonces me pregunto cómo puedo combinar las 3 condiciones en este código.
const removeEmpty = (obj) => { let newObj = {}; Object.keys(obj).forEach((key) => { if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]); else if (obj[key] !== '') newObj[key] = obj[key]; }); return newObj; } var obj = { Sale: { homeownerExemption: '', lastContractDate: '', lastSaleBookNumber: undefined, lastSaleDate: null, saleType: 'Full Sale', salesPrice: '785000', salesPriceCode: 'Sales Price Will Be Computed', seller1FName: '', seller1IdCode: '', seller1FirstName: 'Steve', seller1LastName: 'Miller', seller2FirstName: '', seller2LastName: '', transferType: 'Grant Deed', lastTransactionRecordingDate: '7/8/2021' }, contact: [{ name: 'Tom', age: '', sex: 'male' }] }; const removeEmpty = (obj) => { let newObj = {}; Object.keys(obj).forEach((key) => { if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]); else if (!(obj[key] === "" || obj[key] === null || obj[key] === undefined)) newObj[key] = obj[key]; }); return newObj; }; let test = removeEmpty(obj) console.log(test)Si obj[key] === "" , entonces no es igual a nulo o indefinido. Así pasan la segunda y la tercera parte de tu condición.
Probar
if (!(obj[key] === "" || obj[key] === null || obj[key] === undefined))Debe poner entre paréntesis la condición correctamente. No sea tacaño con los padres, ¡son gratis! Una forma razonable podría ser así:
((obj[key] !== '') || (obj[key] !== null) || (obj[key] !== undefined)) Su condición tiene un extra ( después del segundo || .