如何使用javascript在包含json对象的变量上实现map方法



>我正在尝试在变量中应用金钱格式化程序,因为它只有在我已经推送数组后才能进行格式化。我是否可以使用 map 格式化包含多个 json 对象的变量?例如:

for (var j = 0; j < totalOfPurchased.length; j++) {
// Declare Variables Containing Extend Details
var purchasedProductNested = totalOfPurchased[j].purchasedProduct;
var quantityOfPurchasedNested = totalOfPurchased[j].quantityPurchased;
var totalOfPurchasedNested = totalOfPurchased[j].totalOfPurchased;
var totalOfDiscountsPurchasedNested = totalOfPurchased[j].discountsToConsider;
// Here's The Point I'm Having Trouble
totalOfPurchasedNested = totalOfPurchasedNested.map(v => v.replace(/./g, "").replace(",", "."));
// Final JSON Array Containing Extend Details
var allResponseTwoWithExtendDetails = {
product: purchasedProductNested,
quantity: quantityOfPurchasedNested,
totalPurchased: totalOfPurchasedNested,
totalDiscounts: totalOfDiscountsPurchasedNested
};
// Push Group With Received JSON In Native Array
receivedDataOne.push(allResponseTwoWithExtendDetails);
}

- JSFiddle中的实时项目。

当我尝试将映射应用于变量时,打印了一个错误,说totalOfPurchasedNested它不是一个函数:C

totalOfPurchasedNested = totalOfPurchasedNested.map(v => v.replace(/./g, "").replace(",", "."));

我打算使用这个数组,格式化为最佳产品销售的分组和会计linQ函数,例如:

{product: "botijão 13KG", quantity: "10", totalPurchased: "220,00", totalDiscounts: "200,00"}
{product: "botijão 13KG", quantity: "4", totalPurchased: "208,00", totalDiscounts: "0,00"}
{product: "botijão 13KG", quantity: "13", totalPurchased: "666,00", totalDiscounts: "10,00"}

我将清理这个最后的array,但这就是我希望能够在包含json的变量中的map函数中使用的内容,以便我可以格式化正在存储的资金,并感谢您的帮助:D

{product: "botijão 13KG", quantity: 9, totalOfPurchasedNested: 26901.97},
{product: "botijão 25KG", quantity: 4, totalOfPurchasedNested: 4000.96}

如果我理解正确,您不再需要map因为您已经在数组中的每个对象上运行循环。

你这里的代码已经在那里了:totalOfPurchasedNested = totalOfPurchasedNested.replace(/./g, "").replace(",", "."));

我在这里分叉了你的小提琴: https://jsfiddle.net/vzy29zju/

1- 如果需要,.map不会修改数组数据

,您可以使用.forEach

2-totalOfDiscountsPurchasedNested不是数组,而是字符串,所以你最好使用

totalOfPurchasedNested = totalOfPurchasedNested.replace(/./g, "").replace(",", ".");

查看更新的小提琴

最新更新