简体   繁体   English

将 json object 解析为数组

[英]parse json object to array

i am stuck with this and i don't know how to do it.我坚持这一点,我不知道该怎么做。 so basically i got this json data from api:所以基本上我从 api 得到了这个 json 数据:

json数据

this is what i'm getting in the console when i log the data:这是我在记录数据时在控制台中得到的内容:

控制台日志

what i want to do is to parse this object to take the id,title,url,thumbnailUrl and store them to a new array我想要做的是解析这个 object 以获取 id,title,url,thumbnailUrl 并将它们存储到一个新数组中

code to get the data:获取数据的代码:

const [photo,setPhoto] = useState([])
    const newPhotosLocally = photo

    useEffect(() => {
        axios.get("https://jsonplaceholder.typicode.com/photos").then(
            result => {
                setPhoto(result.data)
            }
        )

    },[])

hope you can help me and thank you希望你能帮助我,谢谢

Below newData is new array. newData下面是新数组。

var newData = [...result.data];

If you want to take only few properties.如果你只想拿几个属性。 Below will give you new array with only mentioned properties.下面将为您提供仅具有提及属性的新数组。

var newData = result.data.map(({id, title, url, thumbnailUrl}) => ({id, title, url, thumbnailUrl}));

With so many records being fetched from API, also consider if you want to make multiple calls and fetch only what is needed.从 API 获取如此多的记录,还要考虑是否要进行多次调用并仅获取所需的内容。 Also consider if you really want to trim the number of properties as payload is slightly huge.还要考虑你是否真的想减少属性的数量,因为有效负载有点大。

you already have all the data you need.您已经拥有所需的所有数据。 if you need only with some specific fields use map operator.如果您只需要某些特定字段,请使用 map 运算符。

const newData = result.data.map(obj => {id,title,url,thumbnailUrl});

this will give you the required fields, in a new array (map is responsible for the new array).这将为您提供新数组中的必填字段(map 负责新数组)。

you can assign to array batch inside return axios directly.您可以直接在 return axios 中分配给数组批处理。
This is complete code.这是完整的代码。

const [photo,setPhoto] = useState([])
useEffect(() => {
  axios.get("https://jsonplaceholder.typicode.com/photos").then(
      result => {
        // Add bellow here code
        let newData = result.data.map(({id, title, url, thumbnailUrl}) => ({id, title, url, thumbnailUrl}));
        setPhoto(newData);
      }
  )
},[])

You can map on every item returned by the response as given:您可以对响应返回的每个项目进行 map,如下所示:

const [photo,setPhoto] = useState([])
const newPhotosLocally = photo

useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/photos").then(
        result => {
            var dataArray = result.data.map(({id, title, url, thumbnailUrl}) => ({id, title, url, thumbnailUrl}));
            //do something with the array
        }
    )

},[])

This dataArray will contain all the items returned by the api此 dataArray 将包含 api 返回的所有项目

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM