如何从SharePoint列表项获取数组中的总数

时间:2019-05-02 15:39:01

标签: reactjs spfx

我正在使用Reactjs创建一个spfx Web部件。我有一个功能,该功能从SharePoint列表中获取一系列项目,其中包括“小时”的数字列。我需要获得所有已返回小时数的总计,但无法弄清楚该如何计算。

我觉得我缺少一些简单的东西,但是我经历了各种各样的循环,由于某种原因,我无法使其正常工作。我已验证自己是从“小时”列中获取数据的。

我还将声明“我是spfx的新手并做出反应”。 :) TIA寻求任何帮助!

private readItem(): void {
  this.props.spHttpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('Time Off')/items?$select=Title,Id,Hours`,
    SPHttpClient.configurations.v1,
    {
      headers: {
        'Accept': 'application/json;odata=nometadata',
        'odata-version': ''
      }
    }).then((response: SPHttpClientResponse): Promise<ITimeOffItem[]> => {
      return response.json();
    })
    .then((item: ITimeOffItem[]): void => {

      console.log(item); //the data is here including Hours

      this.setState({
        items: item,
        hoursTotal: //????How do I get the sum of "Hours" and assign it to a number in state
      });

    });
}

2 个答案:

答案 0 :(得分:1)

创建一个函数来遍历项目并添加小时数

function countHours(items) {
  if (!items) {
    return 0;
  }

  let total = 0;

  for (let i = 0; i < items.length; i++) {
    total += items[i].Hours;
  }

  return total;
}

const item = [
  { Id: 25, Title: "Comp Time", Hours: 6, ID: 25 },
  { Id: 26, Title: "Comp Time", Hours: 5, ID: 26 },
  { Id: 27, Title: "Work from Home", Hours: 3, ID: 27 },
  { Id: 28, Title: "Comp Time", Hours: 7, ID: 28 },
  { Id: 29, Title: "Work from Home", Hours: 8, ID: 29 },
  { Id: 30, Title: "Holiday", Hours: 8, ID: 30 },
  { Id: 31, Title: "Work from Home", Hours: 32, ID: 31 }
];

console.log(countHours(item));

使用方式

this.setState({
    items: item,
    hoursTotal: countHours(item)
});

您也可以使用reduce

const item = [
  { Id: 25, Title: "Comp Time", Hours: 6, ID: 25 },
  { Id: 26, Title: "Comp Time", Hours: 5, ID: 26 },
  { Id: 27, Title: "Work from Home", Hours: 3, ID: 27 },
  { Id: 28, Title: "Comp Time", Hours: 7, ID: 28 },
  { Id: 29, Title: "Work from Home", Hours: 8, ID: 29 },
  { Id: 30, Title: "Holiday", Hours: 8, ID: 30 },
  { Id: 31, Title: "Work from Home", Hours: 32, ID: 31 }
];
const sum = item.reduce(function(a, b) { return a + b.Hours; }, 0);

console.log(sum)

答案 1 :(得分:-1)

在不知道数据结构是什么样的情况下很难回答这个问题,但是如果您试图对一组数字求和,则可以使用reduce

const hours = [7, 5, 3, 1, 7]

const totalHours = hours.reduce((accumulator, hour) => accumulator + hour)