首页 > 解决方案 > 将 Javascript Map 函数返回的数组保存到新数组

问题描述

我有一个对象数组。我想要一个包含相同元素但仅包含其x属性的新数组。

所以原始数组是:

[{x: "401K", y:1000}, {x: "RSU": y: 6000}]

新数组将是:

["401k", "RSU"]

我努力了:

const legend = this.state.pieChartData.map(a => a.x)

当我传入this.state.pieChartData.map(a => a.x))console.log回调函数时setstate,它会打印正确的数组。但是当 I console.log(this.state.pieLegend)() 它是一个空数组。

  computeTotals(){
    var runningTotal = 0
    var pieArray = []
    var beyondBudget = {}

  const legend = this.state.pieChartData.map(a => a.x)
  console.log("this does not show correct array", legend)
    //filter out all $0 answers
    Object.keys(this.state.data.selectedQuestions)
  .filter(key => Object.values(this.state.data.selectedQuestions[key])[0] != 0)
  .map((key, index) => {
    const value = Object.values(this.state.data.selectedQuestions[key])[0]
    const name = key
    runningTotal += value
    //still not gone beyond budget, add to pie chart
    if(runningTotal <= 1600){
      let pieSlice =
           {
             x: name,
             y: value
           };
      pieArray = pieArray.concat(pieSlice)

    }
    //went beyond budget, add to beyondbudget table data
    else {

          if (Object.keys(beyondBudget).length == 0) {
              beyondBudget[name] = {};
              beyondBudget[name] = runningTotal - 1600;
              let pieSlice =
                   {
                     x: name,
                     y: value - (beyondBudget[name])
                   };
              pieArray = pieArray.concat(pieSlice)
          }
          if (!beyondBudget[name]) {
              beyondBudget[name] = {};
          }
          if (Object.keys(beyondBudget).length > 1) {
              beyondBudget[name] = value;
          }

      }
  })

    this.setState({
      pieChartData: pieArray,
      total: runningTotal,
      beyondBudget: beyondBudget,
      pieLegend: this.state.pieChartData.map(a => a.x)
    }, () => {
      console.log("this shows correct array",  this.state.pieChartData.map(a => a.x));
      console.log("this does not", this.state.pieLegend)
      this.computePiePercentages();

    });

}

我认为问题是我没有返回任何东西。所以我尝试了这个:

const legend = this.state.pieChartData.map(function justName(item){
      console.log("test!")
      return item.x
    }

但是我的测试语句没有打印事件。

标签: javascriptarraysreactjs

解决方案


如图所示,您的setState方法将无法正常工作:

    this.setState({
      pieChartData: pieArray,
      total: runningTotal,
      beyondBudget: beyondBudget,
      pieLegend: this.state.pieChartData.map(a => a.x)
    }, () => {});

您在设置pieLegendthis.state.pieChartData.map(a => a.x)同时设置为pieChartData. 但是因为它同时(并且可能在Object.assign()内部进行),所以 pieChartData 的值在this.state.pieChartData.map(a => a.x)评估时仍然是未定义的,因此 state.pieLegend 也将是未定义的。

在尝试映射它之前,您需要先设置 pieChartData,或者只映射 pieArray 以开始:

this.setState({
    pieChartData: pieArray,
    total: runningTotal,
    beyondBudget: beyondBudget,
    pieLegend: pieArray.map(a => a.x)
}, () => {});

推荐阅读