我正在尝试将新生成的对象推入JavaScript中的数组
我有一个以下形式的数组:
savings: any = [{month: "January", amount: 300}, {month: "February", amount:450}, {month: "March", amount: 500}]
和一个名为 savings_bf 的变量,其值是
savings_bf = 15000
我使用了数组 Savings 和 Savings_bf 中的 amount 值,使用此处提供的解决方案{{3} }以获取输出:
_total_cf = [15300,15750,16250]
我的代码如下;
savings.forEach(s =>s.total_cf = _total_cf)
新的储蓄数组的预期输出应为:
[{month: "January", amount: 300, total_cf: 15300 }, {month: "February", amount:450, total_cf: 15750}, {month: "March", amount: 500 total_cf: 16250}]
实际输出:
[{month: "January", amount: 300, total_cf: [15300,15750,16250]}, {month: "February", amount:450, total_cf: [15300,15750,16250]}, {month: "March", amount: 500 total_cf: [15300,15750,16250]}]
答案 0 :(得分:3)
// You can use following code.
savings.forEach((item, index, array) => {
savings[index].total_cf = _total_cf[index];
});
答案 1 :(得分:2)
您可以使用forEach
提供的回调方法的第二个参数来跟踪索引。由于_total_cf
是一个数组,因此您需要根据索引访问适当的项目。您可以在回调中使用索引,如下所示:
var savings = [{month: "January", amount: 300}, {month: "February", amount:450}, {month: "March", amount: 500}]
var _total_cf = [15300,15750,16250];
savings.forEach((s, index) => s.total_cf = _total_cf[index]) ;
console.log(savings);
答案 2 :(得分:2)
仅.map()
个数组,添加您在循环中更新的运行总计。
const months = [
{month: "January", amount: 300},
{month: "February", amount:450},
{month: "March", amount: 500}
];
const savings = 15000;
let running_total = savings;
const updated_months = months.map( item => {
running_total += item.amount;
return {
month: item.month,
amount: running_total
};
});
console.log( updated_months );
如果由于某种原因您还需要_total_cf
变量来进行其他操作,则可以轻松地再次提取它:
const updated_months = [
{month: "January", amount: 15300},
{month: "February", amount:15750},
{month: "March", amount: 16250}
];
const _total_cf = updated_months.map( item => item.amount );
console.log( _total_cf );
答案 3 :(得分:1)
您可以使用Array.prototype.map
映射数组中的每个对象,并使用其在回调(第二个参数)中提供的 index 来从{{1} }数组。
还可以使用传播运算符_total_cf
与先前的对象属性和...
数组中的新对象属性进行合并:
_total_cf
在代码中,您将整个const savings = [{month: "January", amount: 300}, {month: "February", amount:450}, {month: "March", amount: 500}];
const _total_cf = [15300,15750,16250];
const result = savings.map((obj, idx) => ({...obj, total_cf: _total_cf[idx]}));
console.log(result);
数组分配给您在每次迭代中创建的total_cf
属性。
total_cf
还要对//the entire array is assigned to the `total_cf` property.
savings.forEach(s =>s.total_cf = _total_cf);
的{{1}}数组中的原始对象进行突变。在savings
操作中,将返回一个包含新对象的新数组,其中包含旧的道具以及要添加的新属性。
答案 4 :(得分:0)
您可以使用正确的方法来计算Savings_bf,并且可以一次完成所有操作。
X
答案 5 :(得分:0)
您还可以使用reduce来计算total_cf
尝试以下代码
const savings = [
{month: "January", amount: 300},
{month: "February", amount:450},
{month: "March", amount: 500}
];
const savings_bf = 15000;
savings.reduce((a,b)=>{
b.total_cf = (a[a.length-1] ? a[a.length-1].total_cf : savings_bf) + b.amount
a.push(b)
return a
},[])