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

438
Views
Cómo reemplazar nulo con "-" usando una sola línea en Jquery

Cómo reemplazar null con - usando una sola línea en jQuery

Por ejemplo

 var obj={ "Key1":null, "key2":"I have null", "key3":null }

Rendimiento esperado:

 var obj={ "Key1":"-", "key2":"I have null", "key3":"-" }
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede usar Object.keys y verificar el valor. con una función recursiva con un cierre sobre el objeto iterativo.

 var iter = o => k => o[k] && typeof o[k] === 'object' && Object.keys(o[k]).forEach(iter(o[k])) || o[k] === null && (o[k] = '-'), object = { Key1: null, key2: "I have null", key3: { kje: "test", dfasfd: null, demo: "null demo" } }; Object.keys(object).forEach(iter(object)); console.log(object);

que básicamente resuelve con ES5 en

 var object = { Key1: null, key2: "I have null", key3: { kje: "test", dfasfd: null, demo: "null demo" } }; Object.keys(object).forEach(function iter(o) { return function (k) { if (o[k] && typeof o[k] === 'object') { Object.keys(o[k]).forEach(iter(o[k])); return; } o[k] === null && (o[k] = '-'); }; }(object)); console.log(object);

over 4 years ago · Santiago Trujillo Report

0

Esta función de una línea funcionará:

 function nullToDash(obj){for(e in obj){if(obj.hasOwnProperty(e) && obj[e]===null){obj[e]="-";}}}

Editar: función anterior no minimizada para una mejor comprensión

 function nullToDash(obj){ for(e in obj){ if(obj.hasOwnProperty(e) && obj[e]===null){ obj[e]="-"; } } }
over 4 years ago · Santiago Trujillo Report

0

En una línea, se vería algo así como

 JSON.parse(JSON.stringify(obj).split(":null").join((':\"-"'))); 

 var obj = { "Key1": null, "key2": "I have null", "key3": null } var obj1=JSON.parse(JSON.stringify(obj).split(":null").join((':\"-"'))); console.log(obj1)

Para hacer el código genérico

 $.each( obj, function( key, value ) { if (value == null) value = "-"; });
over 4 years ago · Santiago Trujillo 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!