我有一个看起来像这样的对象数组:
const arr1 = [
{id: 1, name: 'Dave', tax: 123.34543}
{id: 2, name: 'John', tax: 3243.12323}
{id: 3, name: 'Tom', tax: 122.34324}
]
而且我正在尝试舍入税值,因此最后该数组应如下所示:
[
{id: 1, name: 'Dave', tax: 123.34}
{id: 2, name: 'John', tax: 3243.12}
{id: 3, name: 'Tom', tax: 122.34}
]
我尝试像这样使用
map
函数:arr1.map(value => Math.round(value.tax * 100)/100);
但是我没有得到修改后的对象数组,而是得到了一个仅包含
Math.round
结果的数组,如下所示:[ 123.34, 3243.12, 122.34]
我如何映射对象数组以获得如上所述的预期结果。
谢谢。
最佳答案
您可以使用所需值映射新对象。
const
array = [{ id: 1, name: 'Dave', tax: 123.34543 }, { id: 2, name: 'John', tax: 3243.12323 }, { id: 3, name: 'Tom', tax: 122.34324 }],
result = array.map(o => Object.assign({}, o, { tax: Math.round(o.tax * 100) / 100 }));
console.log(result);
关于javascript - 修改对象数组中的对象值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53098658/