Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 618
Prakash Madhak Avatar asked May 30 '26 11:05

Prakash Madhak


1 Answers

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);
like image 86
Nina Scholz Avatar answered Jun 02 '26 01:06

Nina Scholz