我有一个对象,其中一对具有逗号的值。我想删除对象中所有这些值的逗号,并返回修改后的对象。对象如下 -
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)。怎么办呢?
答案 0 :(得分:1)
您可以使用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);
答案 1 :(得分:0)
试试这个会起作用:
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);
答案 2 :(得分:0)
您可以使用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);

<div id="result">
</div>
&#13;
答案 3 :(得分:0)
你可以使用正则表达式而不使用循环。
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