Search code examples
arraysjsonreactjsiterated-function

How can I parse json array from json object?


I have a json object being returned from a get request in reactjs. I am wanting to get key and value items from this.

{"return":"Success",

"Items": [

{"Name":"centracore", "Type":"rollover" ,  "Os":"Windows",  "Level":"1", "Language_Used":"Assembly", "Size":"4mb"},

{"Name":"centracore", "Type":"Atype" ,   "Os":"Linux"  ,  "Level":"3", "Language_Used":"C++"     , "Size":"4mb"},

{"Name":"centracore", "Type":"random" ,  "Os":"OSX"    ,  "Level":"2", "Language_Used":"C"       , "Size":"4mb"}

]}

I noticed I can access the values manually using the code below.

Keep in mind, that this.state.stuff is holding my json object. Is my format json format bad for what I am trying to do?

if(this.state.authenticated ){
            {this.GetPage.bind(this)}
            let x = this.state.stuff; Object.entries(this.state.stuff).map((type,item) => {

            console.log(type[1][0])
            console.log(type[1][1])
            console.log(type[1][2])
          })

Solution

  • As far as I understand you want to be able to get the key and values within the Object Items arrays, so you need to map over items array and then the key, values from the obtained item with Object.entries()

    You can do it like

     if(this.state.authenticated ){
            {this.GetPage.bind(this)}
            this.state.stuff.Items.map((item, index) => {
                 Object.entries(item).forEach([key, value], () => {
                        console.log(key, value)
                 })
    
          })
    

    Working example

    var obj = {"return":"Success",
    
    "Items": [
    
    {"Name":"centracore", "Type":"rollover" ,  "Os":"Windows",  "Level":"1", "Language_Used":"Assembly", "Size":"4mb"},
    
    {"Name":"centracore", "Type":"Atype" ,   "Os":"Linux"  ,  "Level":"3", "Language_Used":"C++"     , "Size":"4mb"},
    
    {"Name":"centracore", "Type":"random" ,  "Os":"OSX"    ,  "Level":"2", "Language_Used":"C"       , "Size":"4mb"}
    
    ]}
    obj.Items.map((item, index) => {
           console.log( item);
           Object.entries(item).forEach(([key, value]) => {
                  console.log(key, value)
           })
    
    })
    

    JSFIDDLE