简体   繁体   English

如何将 json 属性转换为具有键值的多个对象(typescript react)

[英]how to transform json properties to multiple objects with key value (typescript react)

i'm trying to use fetched data form an api in a recharts linechart but i'm having trouble mapping the json data.我正在尝试在 recharts 线图中使用从 api 获取的数据,但在映射 json 数据时遇到问题。 i have an api that return data as shown below, basically count of predictions in each month and 0 if the month doesnt exist but the data is in a format that i can't map through it.我有一个 api 返回如下所示的数据,基本上是每个月的预测计数,如果月份不存在则为 0,但数据的格式我无法通过它 map。 i have a single object in the json data and would like to transform it to multiple objects using key as a value for another key and value as another value for another key.我在 json 数据中有一个 object,我想将其转换为多个对象,使用键作为另一个键的值,使用值作为另一个键的另一个值。 sorry for my bad explanation i don't know how to describe this problem.抱歉我的错误解释我不知道如何描述这个问题。

data format数据格式

[
  {
    "_id": 2022,
    "jan": 1,
    "feb": 0,
    "mar": 0,
    "apr": 0,
    "may": 0,
    "jun": 0,
    "jul": 0,
    "aug": 0,
    "sep": 0,
    "oct": 0,
    "nov": 13,
    "dec": 0
  }
]

format that i want to achieve to use in a state我想要在 state 中使用的格式

[
  {
    "month": "jan",
    "count": 1
  },
  {
    "month":"feb",
    "count":"0"
  },
  {
    "month":"mar",
    "count":"0"
  }
  {
    "month":"apr",
    "count":"0"
  },
  {
    "month":"may",
    "count":"0"
  }
}

i would like to skip the year aswell我也想跳过这一年

linechart code线图代码

import React, { useEffect, useState } from "react";
import {
    LineChart,
    XAxis,
    YAxis,
    CartesianGrid,
    Line,
    Tooltip,
    Legend
} from 'recharts';

const PredictionsMonthLinechart = () => {
    const [d, setD] = useState([
        {
            month: 'jan',
            predictions: 4000,
        },
    ])

    const fetchData = async () => {
        const res = await fetch("http://localhost:5000/query/predictions_per_month");
        const data = await res.json()
            .then(data => {
                setD((Object.keys(data)).map((key) => {
                    return {
                        month: key,
                        predictions: data[key]
                    }
                }))
            })
        console.log(data);
        console.log(d);
    }

    useEffect(() => {

        fetchData();
    }, []);


    return (
        <LineChart width={1100} height={400} data={d}
            margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="month" />
            <YAxis />
            <Tooltip />
            <Legend />
            <Line type="monotone" dataKey="predictions" stroke="#8884d8" />

        </LineChart>
    )
}

export default PredictionsMonthLinechart;

i have tried using Object.entries() but it keeps giving me errors in IDE Object.keys() returns undefined object but atleast it's reading the keys correctly.我试过使用 Object.entries() 但它一直给我错误 IDE Object.keys() 返回未定义 object 但至少它正确读取密钥。

Uncaught Error: Objects are not valid as a React child (found: object with keys {\_id, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec}). If you meant to render a collection of children, use an array instead.

Assuming that data that you get from the request is (as you said):假设您从请求中获得的data是(如您所说):

[
  {
    "_id": 2022,
    "jan": 1,
    "feb": 0,
    "mar": 0,
    "apr": 0,
    "may": 0,
    "jun": 0,
    "jul": 0,
    "aug": 0,
    "sep": 0,
    "oct": 0,
    "nov": 13,
    "dec": 0
  }
]

Then this line can't be correct because data is an array, not an object:那么这一行就不可能是正确的,因为data是一个数组,而不是 object:

setD((Object.keys(data)).map((key) => {

Adapting the code to this should make it compile (it also contains a filter for the year property):将代码改编成这样应该可以编译(它还包含一个用于 year 属性的filter ):

.then(data => {
  setD((Object.keys(data[0])).filter(key => key !==  "_id").map((key) => {
    return {
      month: key,
      predictions: data[0][key]
    }
  }))
})

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

相关问题 如何使用 Typescript 转换与 React - How to use Typescript Transform with React 如何在保存到反应 state 之前更改 JSON 对象数组中键的值 - How can I change the value of a key in the JSON objects array before being saved into the react state 如何循环遍历对象数组并使用 typescript 创建仅具有某些属性的新对象数组并做出反应? - How to loop through array of objects and create a new array of objects with only certain properties using typescript and react? 如何将键值对列表转换为TypeScript中的对象列表? - How to convert a list of key-value pairs into list of objects in TypeScript? React/Axios 基于键/值合并多个对象数组 - React/Axios merge multiple array of objects based on key/value 如何为 TypeScript React 应用程序设置键/值默认值 state - How to set key/value default state for TypeScript React app TSX React - 如何使用多个 JSON 对象索引 JSON API 数据 - TSX React - How to index JSON API Data with multiple JSON Objects 如何在 React 应用程序中读取全局键值属性 - How to read global key value properties in a React application 将此 React 代码段转换为 Typescript? - Transform this React snippet to Typescript? 如何在反应中更新对象数组中的单个键值对? - How to update a single key value pair in an array of objects in react?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM