w2olves
w2olves

Reputation: 2329

Remove special character from property of a javascript object in an array

I have a simple javascript array of objects like this:

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

My dataList array has hundreds of such objects. I want to remove the comma from the SBusinessnameLegal property or any other property that may have a comma. I would like to replace it by a space

So my end object would be something like

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

I have tried converting the array to a json string then .replace(',', ' ');

But that isnt working. Any ideas or pointers on how I can pass an array to a function and it would strip a particular character from all properties of objects in the array ? TIA

Upvotes: 3

Views: 3894

Answers (2)

gurvinder372
gurvinder372

Reputation: 68393

try this

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

If you have this in an array then

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

Upvotes: 2

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27212

Try any of these scenarios :

  • for single object having multiple properties with comma(,)

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

  • For array of objects try this.

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

Upvotes: 4

Related Questions