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

422
Views
How to Replace null with "-" using single line in Jquery

How to Replace null with - using single line in jQuery

For Example

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

    }

Expected Output:

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

}
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You could use Object.keys and check the value. with a recursive function with a closure over the iterating object.

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

which basically resolves with ES5 in

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

about 4 years ago · Santiago Trujillo Report

0

This one-line function will work:

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

Edit: Unminified above function for better understanding

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

0

In one line, It would look something like

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)

To make the code generic

$.each( obj, function( key, value ) {
 if (value == null) 
   value = "-";
});
about 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!