簡體   English   中英

在 React 中使用嵌套對象映射數組

[英]Mapping through array in React with nested objects

對於一個學校項目,我正在制作一個儀表板,我想在其中可視化一些數據。 到目前為止,我已經得到了它,我可以將數據加載到響應的前端。

現在我想從數組中獲取某些值。 但由於它是一個相當大的數組,我不確定如何循環遍歷它。

數據如下所示: 在此處輸入圖像描述

我想為每個 object 設置 _value,以便最終可以將其從 rechart 加載到面積圖中。

面積圖的代碼:

<AreaChart
    width={1550}
    height={400}
    data={this.getMachineData()}
    margin={{
        top: 10,
        right: 30,
        left: 0,
        bottom: 0,
    }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis dataKey="_table" />
<Tooltip />
<Area type="monotone" dataKey="uv" stackId="1" stroke="#8884d8" fill="#8884d8" />
<Area type="monotone" dataKey="pv" stackId="1" stroke="#82ca9d" fill="#82ca9d" />
<Area type="monotone" dataKey="amt" stackId="1" stroke="#ffc658" fill="#ffc658" />
<Legend />
    <Bar dataKey="_value" fill="#8884d8" />
    <Bar dataKey="uv" fill="#82ca9d" />
</AreaChart>

我已經做了一個方法,但是還沒有實現:

getMachineData(data) {
    console.log(data)
    const result = data.map((innerArray) => {
        console.log(innerArray)
        // Map over the inner array
        return innerArray.map((item) => {
            // Return an object with only the properties you need
            return ({
                time: item._time,
                value: item._value
            });
        });
    })
    console.log(result)
    return result;
};

I was thinking of looping through the object myself with the.map function but since they are objects within objects I'm not sure how to go about this.

不確定對象中的對象是什么意思。 我在上圖中看到的是數組中的一個數組(包含 816 個對象)。 因此,使用 map function 的更簡單方法是:

 const data = [ [ { _time: 1, _value: 2 }, { _time: 3, _value: 4 }, { _time: 5, _value: 6 }, { _time: 7, _value: 8 }, ] ] // Map over the outer array const result = data.map((innerArray) => { // Map over the inner array return innerArray.map((item) => { // Return an object with only the properties you need return ({ time: item._time, value: item._value }); }); }) console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM