gpt4 book ai didi

javascript - 如何将新数据合并到旧数组中?

转载 作者:行者123 更新时间:2023-12-01 01:26:33 25 4
gpt4 key购买 nike

我有一个这样的数组。这里我只包含了 5 个字段,但实际上我有大约 45 个字段名。

0: {id:1, product_name: 'aaa', val1:1, val2:2, val3:4}
1: {id:2, product_name: 'bbb', val1:1, val2:2, val3:4}
2: {id:3, product_name: 'ccc', val1:1, val2:2, val3:4}
3: {id:4, product_name: 'ddd', val1:1, val2:2, val3:4}

我想获得 val1、val2 和 val3 的总和并显示在总计列中,并将“%”符号附加到这 3 个值。

我按照以下步骤获取总和并附加 %

temp = temp.map((row) => {
const newRow= {};
let total = 0;

total = row['val1'] +
row['val2'] +
row['val3'] +

newRow['total'] = total;

newRow['val1'] = row['val1'] + '%';
newRow['val2'] = row['val2'] + '%';
newRow['val3'] = row['val3'] + '%';

return newRow;
});

使用此代码,我仅返回数组中的 val1、val2 和 val3。如何附加其他 42 列并获得最终结果。

最佳答案

你可以这样做

var temp = [{id:1, product_name: 'aaa', val1:1, val2:2, val3:4},
{id:2, product_name: 'bbb', val1:1, val2:2, val3:4},
{id:3, product_name: 'ccc', val1:1, val2:2, val3:4},
{id:4, product_name: 'ddd', val1:1, val2:2, val3:4}];

temp = temp.map(row => {
const newRow = row;
let total = 0;

total = parseInt(row['val1']) +
parseInt(row['val2']) +
parseInt(row['val3']);

newRow['total'] = total;

newRow['val1'] = row['val1'] + '%';
newRow['val2'] = row['val2'] + '%';
newRow['val3'] = row['val3'] + '%';

return newRow;
});
$("#result").append(JSON.stringify(temp) + "<br />");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='result'>

</div>

关于javascript - 如何将新数据合并到旧数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53720356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com