简体   繁体   中英

Get all key, values from nested json

I' trying to fetch some json data, structured like so:

{"Points": 
       {"90": 
             {"0": {"name": "John Phillip", "slug": "john"},
             {"1": {"name": "Mark Anthony", "slug": "mark"},
             ...
       },
       ...
 }

With:

 async getData(93) {
      const res = await fetch("/json/sample.json");
      const data = await res.json();

      // round to the lowest multiple of five 5: 92->90, 93->90
      const roundToLowest5 = x => Math.floor(x/5)*5

      // Here a I access the key of '90', from outer key 'Points'
      console.log(data.Points[roundToLowest5(value).toString()])

      return this.setState({ data });
    }

So far, console shows me all data for my outer key 'Points':

{0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}, 6: {…}, 7: {…}, 8: {…}, 9: {…}, 10: {…}, 11: {…}}

Considering that all index keys here ("0", "1", "2"...) are strings, how do I get all key, values for each index key?

Expected output:

{"name":"John Phillip", "slug": "john"}, {"name":"Mark Anthony", "slug":"mark"}...

You can use Object.values to return an array of values of all keys

  console.log(Object.values(data.Points[roundToLowest5(value).toString()]))
  //this will return [{"name":"John Phillip", "slug": "john"}, {"name":"Mark Anthony", "slug":"mark"}...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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