从数组中的javascript对象的属性中删除特殊字符

时间:2017-04-11 05:57:24

标签: javascript json

我有一个简单的javascript对象数组,如下所示:

  $scope.dataList = [];
                var obj = { "SLicenseNo": "NM-2136", "SBusinessnameLegal": "Luxury Auto Mall of Sioux Falls, Inc.", "SNameFirstSoleproprietor": "Edward"};
                $scope.dataList.push(obj);

我的dataList数组有数百个这样的对象。我想从SBusinessnameLegal属性或可能有逗号的任何其他属性中删除逗号。我想用空格替换它

所以我的最终目标就像是

 obj = { "SLicenseNo": "NM-2136", "SBusinessnameLegal": "Luxury Auto Mall of Sioux Falls Inc.", "SNameFirstSoleproprietor": "Edward"};

我尝试将数组转换为json字符串,然后转换为.replace(',','');

但那不起作用。关于如何将数组传递给函数的任何想法或指针,它会从数组中对象的所有属性中删除特定字符? TIA

2 个答案:

答案 0 :(得分:3)

尝试以下任何一种情况:

  • 表示具有逗号(,)
  • 的多个属性的单个对象

var obj = { 
    "SLicenseNo": "NM-2136", 
    "SBusinessnameLegal": "Luxury Auto Mall of Sioux Falls, Inc.",
    "SNameFirstSoleproprietor": "Edward"
};

var newObj = {};
for (var i in obj) {
  newObj[i] = obj[i].replace(',','');
}

console.log(newObj);

  • array of objects试试这个。

var dataList = [
{ 
    "SLicenseNo": "NM-2136", 
    "SBusinessnameLegal": "Luxury Auto Mall of Sioux Falls, Inc.",
    "SNameFirstSoleproprietor": "Edward"
},{ 
    "SLicenseNo": "NM-2136, Test", 
    "SBusinessnameLegal": "Luxury Auto, Mall of Sioux Falls Inc.",
    "SNameFirstSoleproprietor": "Edward"
}];

dataList.map(function(item) {
  var keyse = Object.keys(item);
  for (var i in keyse) {
    item[keyse[i]] = item[keyse[i]].replace(',','');
  }
});

console.log(dataList);

答案 1 :(得分:1)

试试这个

Object.keys(obj).each( function(key){ obj[key] = obj[key].replace(/,/g, " ") } );

如果你有一个数组,那么

$scope.dataList = $scope.dataList.map( function( obj ){
  Object.keys(obj).each( function(key){ obj[key] = obj[key].replace(/,/g, " ") } );
  return obj;
});