将多个数组对象转换为单个对象

时间:2018-11-04 17:58:05

标签: javascript reactjs

我在创建图形的地方制作了一个React应用。

图形只接受这种格式的数据

0: {x: 0, y: 10.7279501}
1: {x: 0, y: 10.73239994}
2: {x: 0, y: 10.73684978}
3: {x: 0, y: 10.7413168}
4: {x: 0, y: 10.74576664}

所以现在我正在做这样的事情

 for (let j=0; j<data.peaks[0]["eic"]["rt"].length; j++) {
             this.data.push({
                 y: data.peaks[0]["eic"]["intensity"][j],
                 x: data.peaks[0]["eic"]["rt"][j]
             })
         }

         for (let j=0; j<data.peaks[1]["eic"]["rt"].length; j++) {
            this.data1.push({
                y: data.peaks[1]["eic"]["intensity"][j],
                x: data.peaks[1]["eic"]["rt"][j]
            })
        }

        for (let j=0; j<data.peaks[2]["eic"]["rt"].length; j++) {
            this.data2.push({
                y: data.peaks[2]["eic"]["intensity"][j],
                x: data.peaks[2]["eic"]["rt"][j]
            })
        }

但这看起来并不整洁,我的意思是创建三个变量(this.data, this.data1, this.data2(它甚至不是动态的)

我正在考虑做一些整洁的事情,以便可以像this.data1, this.data2, this.data3这样的事情来代替this.data[0], this.data[1], this.data[2]

我最终将像这样传递我的数据

   <VictoryStack>
        <VictoryArea name="area-1" data={this.data}/>
        <VictoryArea name="area-1" data={this.data1}   style={{ data: { fill: "#c43a31" } }}/>
        <VictoryArea name="area-1" data={this.data2}/>
  </VictoryStack>

有人可以帮助我做什么吗?

我自己做了

for (let i=0; i<data.peaks.length; i++) {
   this.x.push(data.peaks[i]["eic"]["intensity"])
   this.y.push(data.peaks[i]["eic"]["rt"])
} 

  for (let i=0; i <this.x.length; i++  ) {
      this.data.push({
          x: this.x[i],
          y: this.y[i]
      })
  }

但这是在创建像这样的数据

 (3) [{…}, {…}, {…}]
 0:{id: "SAMPLE_#SPMJXVC_1_2", x: Array(963), y: Array(963)}
 1: {id: "SAMPLE_#SPMJXVC_1_3", x: Array(964), y: Array(964)}
 2: {id: "SAMPLE_#SPMJXVC_1_1", x: Array(954), y: Array(954)}

1 个答案:

答案 0 :(得分:1)

创建一组VictoryArea个道具:

 const areas = data.peaks.map(peak => ({
     data: peak.eic.rt.map((x, i) => ({ x, y: peak.eic.intensity[i] })),
 }));

然后,您可以自定义样式和其他内容:

 areas[1].style = { data: { fill: "#c43a31" }  };

然后映射这些区域以反应元素:

<VictoryStack>
    {areas.map(props => (<VictoryArea name="area-1" {...props} />))}
</VictoryStack>