简体   繁体   中英

How do I pull a nested object out of an array with an api request returned json?

I have an API that I am calling to return a query. This query's format cannot be changed to be easier to manipulate. It has a nested array within it that I need to associate with the data from the higher levels.

Specifically, I am trying to pull the higher level id field and and the "value" field within "column_values" and associate them with one another preferably within a new array. I feel like the answer is here but I just can't grasp how to pull the data in the correct format and associate it together. Most of the comment lines can probably be ignored, they are my other attempts at making the syntax work correctly. Sorry about the mess. I'm really new to this.

    const axios = require('axios')



const body = {
    query: ` query {boards(ids:307027197) {name, items {name id column_values(ids:lockbox_) {title id value text}}}} `,
  }
console.log("Requesting Query....");


function getApi (callback){
    setTimeout(function() {axios.post(`https://api.monday.com/v2`, body, {
        headers: {
            MY_API_KEY_DATA
          },
      })
      .catch(err => {
        console.error(err.data)
      })
      .then(res => {
          var queried = res
          var array = queried.data.data.boards[0].items
                  //console.log(queried)
                  //console.log(array)
             console.log(array.length)
                  //console.log("Total Items:", array.length)
          var i;
          for (i = 0; i < array.length; i++){

            callback(queried.data.data.boards[0].items)

          //callback([(queried.data.data.boards[0].items[i].column_values[0])])

        }
    }, 0);
})
};
getApi(callback => {
    console.log(callback)

            //console.log(parsed)
                //output for above
                //{"name":"address","id":"1234","column_values": 
                //[{"title":"Lockbox#","id":"lockbox_","value":"\"31368720\"","text":"31368720"}]}

            //console.log(JSON.parse(parsed))
             //output for above
            //[
            //       {
            //           name: 'address',
            //           id: '353428429',
            //           column_values: [ [Object] ]
            //       }
            //]
});
setTimeout(function() {
console.log("Query Returned")},1000);

From your data, column_values is an array with objects in it. For an array, you will have to access it with the key. For your case, if your data is like var data = { "name":"address", "id":"1234", "column_values": [{"title":"Lockbox#","id":"lockbox_","value":"\"31368720\"","text":"31368720"}] }

You can access the id of column_values as data.column_values[0].id

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