从对象属性值中删除逗号

我有一个对象,其中一对具有逗号的值。 我想删除对象中所有这些值的逗号并返回修改后的对象。 对象如下 –

var obj = [ { id: 1, Product1: "Table", Phone1: "9878987", Price:"21,000"}, { id: 2, Product1: "Chair", Phone1: "9092345", Price:"23,000"}, { id: 3, Product1: "Cupboard", Phone1: "9092345", Price:"90,000"} ]; alert(JSON.stringify(obj)); 

我想删除价格值中的逗号(例如-23,000 ==> 23000)。 如何才能做到这一点?

您可以使用Array.prototype.forEach()迭代所有项目并修改item.Price

 var obj = [{id: 1,Product1: "Table",Phone1: "9878987",Price:"21,000"},{id: 2,Product1: "Chair",Phone1: "9092345",Price:"23,000"},{id: 3,Product1: "Cupboard",Phone1: "9092345",Price:"90,000"}]; obj.forEach(function(item) { item.Price = item.Price.replace(/,/, ''); }); console.log(obj); 

试试这个会起作用:

 var obj = [ { id: 1, Product1: "Table", Phone1: "9878987", Price:"21,000"}, { id: 2, Product1: "Chair", Phone1: "9092345", Price:"23,000"}, { id: 3, Product1: "Cupboard", Phone1: "9092345", Price:"90,000"} ]; for (var i in obj) { var Price = obj[i].Price.replace(',',''); obj[i].Price = Price; } console.log(obj); 

工作小提琴: https //jsfiddle.net/pn3u8pdh/

您可以使用RegEx替换。 这适用于字符串中的任意数量的逗号。

 var obj = [{ id: 1, Product1: "Table", Phone1: "9878987", Price: "1,21,000" }, { id: 2, Product1: "Chair", Phone1: "9092345", Price: "23,000" }, { id: 3, Product1: "Cupboard", Phone1: "9092345", Price: "90,000" }]; var modifiedArray = obj.map(function(currentObj) { var replaceRegex = new RegExp(",", "g"); currentObj.Price = currentObj.Price.replace(replaceRegex, ""); return currentObj; }); document.querySelector("#result").innerHTML = JSON.stringify(modifiedArray); 
 

你可以使用正则表达式而不使用循环。

 var obj= ... //your array obj= JSON.stringify(obj); obj= obj.replace(/(?=,(?!"))(,(?!{))/g,""); obj= JSON.parse(obj) //you get you object without , in between your values