如何用数组对象中的空字符串替换未定义的值?

时间:2016-01-16 07:28:31

标签: javascript arrays json underscore.js

数组对象:

 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 "
        }]
    }

预期解决方案:

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 "
    }]
}

有没有使用underscore.js做到这一点的解决方案?有什么想法吗?优雅的解决方案?

3 个答案:

答案 0 :(得分:6)

您可以使用此

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

Demo Link Here

答案 1 :(得分:2)

这是一个非常快速的解决方案,我还没有对它进行基准测试,但请参阅下面的解决方案或jsbin:https://jsbin.com/xinuyi/2/edit?html,js,output

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 "
   }]
};

var updatedList = _.map(jsonList.list, function(object, index) {
    return _.mapObject(object, function(val, key) {
        return (val === undefined) ? "" : val;
    });  
});

答案 2 :(得分:1)

对于延迟道歉,如果您不关心修改现有数组及其值,那么这可能会更快地提高性能。如果您可以使用vanilla js本地执行任何操作,那么在我看来,这应该始终用于任何库。

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

您可以在https://jsbin.com/xinuyi/3/edit?html,js,output

上查看jsbin上的最新版本