Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace undefined values with empty string in an array object?

Array object:

 var jsonList= {
        "list": [{
            "COLUMN_NAME": "control_master_id",
            "REFERENCED_COLUMN_NAME": "control_master_id",
            "REFERENCED_TABLE_NAME": "tbi_controls_master",
            "TABLE_NAME": "tbi_widget_controls"
        }, {
            "COLUMN_NAME": "authorization_id",
            "REFERENCED_COLUMN_NAME": "authorization_id",
            "REFERENCED_TABLE_NAME": "tbi_authorization_master",
            "TABLE_NAME": "tbi_controls_master"
        }, {
            "COLUMN_NAME": undefined,
            "REFERENCED_COLUMN_NAME": undefined,
            "REFERENCED_TABLE_NAME": undefined,
            "TABLE_NAME": "tbi_widget_controls "
        }]
    }

Expected solution:

var jsonList={
    "list": [{
        "COLUMN_NAME": "control_master_id",
        "REFERENCED_COLUMN_NAME": "control_master_id",
        "REFERENCED_TABLE_NAME": "tbi_controls_master",
        "TABLE_NAME": "tbi_widget_controls"
    }, {
        "COLUMN_NAME": "authorization_id",
        "REFERENCED_COLUMN_NAME": "authorization_id",
        "REFERENCED_TABLE_NAME": "tbi_authorization_master",
        "TABLE_NAME": "tbi_controls_master"
    }, {
        "COLUMN_NAME": "",
        "REFERENCED_COLUMN_NAME": "",
        "REFERENCED_TABLE_NAME": "",
        "TABLE_NAME": "tbi_widget_controls "
    }]
}

Is there any solution to do this using underscore.js?Any ideas? Elegant solutions?

like image 390
SVK Avatar asked Jan 16 '16 07:01

SVK


2 Answers

You can use this

var updatedList = JSON.stringify(jsonList.list, function (key, value) {return (value === undefined) ? "" : value});

Demo Link Here

like image 145
Shrinivas Pai Avatar answered Oct 14 '22 00:10

Shrinivas Pai


Apologies for the delay, if you don't care about modifying the existing array and its values then this will probably be a lot quicker performance wise. If you can do anything natively using vanilla js then this should always be used over any libraries in my opinion.

jsonList.list.forEach(function(obj) {
  for(var i in obj) { 
    if(obj[i] === undefined) {
      obj[i] = '';
    }
  }
});

You can see the latest version on jsbin here https://jsbin.com/xinuyi/3/edit?html,js,output

like image 43
Jonathan Warykowski Avatar answered Oct 14 '22 00:10

Jonathan Warykowski