简体   繁体   English

无法使用 Javascript 从对象数组中添加行和和列和

[英]Can not add row sum and column sum from array of objects using Javascript

I have some array of objects and I need to calculate the total value of each row and total values of each column and finally I will add new key to each object using Javascript.我有一些对象数组,我需要计算每行的总值和每列的总值,最后我将使用 Javascript 为每个 object 添加新键。 I am explaining my code below.我在下面解释我的代码。

my input is like below.我的输入如下。

let book_data= [ 
    { BranchName: 'Deeksha, Thanisandra, Bengaluru',
        Uniform: 2,
        Shoes: 1,
        Accessories: 1,
        Books: 5,
     },
      { BranchName: 'Deeksha, Thanisandra, Bengaluru',
        Uniform: 2,
        Shoes: 3,
        Accessories: 4,
        Books: 5,
      }
    ]

Here I need to add one more column ie-Grand total to each row and this should contain the sum of all key value rather than BranchName .在这里,我需要在每一行中再添加一列, ie-Grand total ,这应该包含所有键值的总和,而不是BranchName Similarly again I need to append one more new record as last row and it should contant total value of each column.同样,我需要 append 再添加一条新记录作为最后一行,并且它应该包含每列的总值。 I am giving my sample output below.我在下面给出我的样品 output。

在此处输入图像描述

I am explaining my code below.我在下面解释我的代码。

for(let i=0; i<book_data.length; i++) {
        let grandRowTotal = 0;
        for(let key in book_data[i]) {
            if(key !== 'BranchName') {
                console.log('key', book_data[i][key]);
                grandRowTotal += parseInt(book_data[i][key]);
            }
        }
        book_data[i]['Grand Total'] = grandRowTotal;
        console.log('grandRowTotal', book_data[i],book_data);

    }

As per my code its not giving the expected result.根据我的代码,它没有给出预期的结果。 I need here the sum of each row and column value as per my sample output above.我需要根据上面的示例 output 的每行和列值的总和。

I have created an extra array to keep track of the columns.我创建了一个额外的数组来跟踪列。

  1. Basically what I do below is loop through the original array of book_data .基本上我在下面做的是遍历book_data的原始数组。
  2. In each iteration i also loop through the columns data for each book.在每次迭代中,我还会遍历每本书的columns数据。
  3. This allows me to both modify the GrandTotal object and the RowTotal data这允许我修改GrandTotal object 和RowTotal数据

In your question you have two loops to loop through the book data.在您的问题中,您有两个循环来遍历书籍数据。 This is not necessary.这不是必需的。 Since its an array you can simply use the forEach method on an array.由于它是一个数组,您可以简单地在数组上使用forEach方法。

Hope this helps:)希望这可以帮助:)

 var book_data = [{ BranchName: 'Deeksha, Thanisandra, Bengaluru', Uniform: 2, Shoes: 1, Accessories: 1, Books: 5, }, { BranchName: 'Deeksha, Thanisandra, Bengaluru', Uniform: 2, Shoes: 3, Accessories: 4, Books: 5, } ]; var ColumnTotals = { BranchName: 'Grand Total' }; var columns = ['Uniform', 'Shoes', 'Accessories', 'Books']; book_data.forEach(b => { let rowTotal = 0; columns.forEach(i => { if (b[i] === undefined) { return; } ColumnTotals[i] = ColumnTotals[i] || 0; ColumnTotals[i] += b[i]; rowTotal += b[i]; }) b.RowTotal = rowTotal; }); // Calculate RowTotal for ColumnsTotals columns.forEach(i => { ColumnTotals.RowTotal = ColumnTotals.RowTotal || 0; ColumnTotals.RowTotal += ColumnTotals[i]; }) // Adding ColumnTotals to the Array book_data.push(ColumnTotals); console.log('BookData', book_data); console.table(book_data);

you need an object to keep the summary data, I change your code to this.您需要一个 object 来保存摘要数据,我将您的代码更改为此。
the fields of summary object will be added dynamically and you don't need to declare a variable for each field. summary object 的字段将被动态添加,您不需要为每个字段声明一个变量。

It has two advantages:它有两个优点:
1. this is beneficial when each row has different fields. 1. 当每行有不同的字段时,这是有益的。
2. when in the future a field like car: 10 is added to the data you don't need to change your code. 2.当将来像car: 10这样的字段被添加到您不需要更改代码的数据中时。

let book_data = [
  {
    BranchName: 'Deeksha, Thanisandra, Bengaluru',
    Uniform: 2,
    Shoes: 1,
    Accessories: 1,
    Books: 5,
  },
  {
    BranchName: 'Deeksha, Thanisandra, Bengaluru',
    Uniform: 2,
    Shoes: 3,
    Accessories: 4,
    Books: 5,
  },
]

// the last row that show the summary
const summary = { BranchName: 'Grand Total', GrandTotal: 0 }
for (let i = 0; i < book_data.length; i++) {
  let grandRowTotal = 0
  for (let key in book_data[i]) {
    if (key !== 'BranchName') {
      const amount = parseInt(book_data[i][key])
      grandRowTotal += amount
      // calc the summary
      if (summary[key] === undefined) {
        summary[key] = 0
      }
      summary[key] += amount
      summary['GrandTotal'] += amount
    }
  }
  book_data[i]['GrandTotal'] = grandRowTotal
}
book_data.push(summary)

console.log(book_data)

Your problem is that book_data[i] is an object instead of an array, so you can't make use of for .你的问题是book_data[i]是一个 object 而不是一个数组,所以你不能使用for

But, you can use Object.keys() to get an array of object keys, then iterate like you are normally doing:但是,您可以使用Object.keys()来获取 object 键的数组,然后像往常一样进行迭代:

let key in Object.keys(book_data[i]) // instead of 'let key in book_data[i]' in your for

This should be enough to solve it这应该足以解决它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM