【问题标题】:How to properly push a new object with multiple element into an array?如何正确地将具有多个元素的新对象推送到数组中?
【发布时间】:2020-01-08 07:02:20
【问题描述】:

我正在尝试将新生成的对象推送到 JavaScript 中的数组中

我有一个表单数组:

savings: any = [{month: "January", amount: 300}, {month: "February",  amount:450}, {month: "March", amount: 500}]

以及一个名为 savings_bf 的变量;

savings_bf = 15000 

我使用数组 savingssavings_bf 中的 amount 值来计算运行总计,使用此处提供的解决方案 https://stackoverflow.com/a/57737436/11849137获取输出:

_total_cf = [15300,15750,16250] 

我的代码如下所示;

savings.forEach(s =>s.total_cf = _total_cf)

savings 数组的预期输出应该是:

[{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]}]

【问题讨论】:

    标签: javascript html arrays typescript


    【解决方案1】:

    只需.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 );

    【讨论】:

    • 与此相关。如果我希望 _total_cf 的第一个值到 _saving_bf 的初始值 = 15000,得到 [15000,15300,15750,16250] 的输出,该怎么办?
    • 只是通过传播_total_cf将它添加到数组前面? const series = [ _saving_bf , ..._total_cf ]Array.unshift( 15000 ) 将其推送到数组的开头?有很多可能性,但哪种最合适取决于代码的其余部分和您的样式偏好。
    【解决方案2】:

    您可以使用提供给forEach 的回调方法的第二个参数来跟踪索引。由于_total_cf 是一个数组,因此您需要根据索引访问适当的项目。您可以在回调中使用 index 如下:

    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);

    【讨论】:

      【解决方案3】:

      您可以使用Array.prototype.map 来映射数组中的每个对象,并使用它在回调(第二个参数)中提供的索引_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);
      

      另外,您正在改变forEachsavings 数组中的原始对象。在map 操作中,将返回一个新数组,其中包含新对象,其中包含旧道具以及您要添加的新属性。

      【讨论】:

        【解决方案4】:

        你也可以使用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
        },[])
        

        【讨论】:

          【解决方案5】:

          您可以使用正确的方法来计算您的 Savings_bf,并且您可以一次完成所有操作。

              var savings = [{month: "January", amount: 300}, {month: "February",  amount:450}, {month: "March", amount: 500}];
              var savings_bf = 15000 ;
             savings.forEach(function(val) {
            //  console.log(val);
          val['savings_bf'] = parseInt(savings_bf)+val['amount'];
          });
              console.log(savings);
          

          【讨论】:

          • @HarunYilmaz 我已经用 javascript 更新了代码。
          【解决方案6】:
          //  You can use following code.
          savings.forEach((item, index, array) => {
              savings[index].total_cf = _total_cf[index];
          });
          

          【讨论】:

            猜你喜欢
            • 2020-02-13
            • 2016-01-20
            • 2020-07-14
            • 1970-01-01
            • 1970-01-01
            • 2013-01-21
            • 2015-10-14
            • 1970-01-01
            相关资源
            最近更新 更多