Home > Blockchain >  How to format response to populate select in react native
How to format response to populate select in react native

Time:10-26

Im trying to format the items that came in Terminals field to an Array of { key, label } in order to populate a dropdown

    Object {
        "Status": "SUCCESS",
        "Terminals": Object {
          "0": Object {
            "name": "GENESIS- DEMO Terminal",
            "term_id": "GENESIS",
          },
          "1": Object {
            "name": "GENESIS- DEMO Terminal",
            "term_id": "GENESIS",
          },
          "name": "",
          "term_id": "",
        },
        "TotalCount": 1
    }

CodePudding user response:

You have Total count in your response, so based on that total count read each data from the object and push it to the options variable A simple for loop can solve this problem

Check my code

let response = {
        "Status": "SUCCESS",
        "Terminals":  {
          "0": {
            "name": "GENESIS- DEMO Terminal",
            "term_id": "GENESIS",
          },
          "1": {
            "name": "GENESIS- DEMO Terminal",
            "term_id": "GENESIS",
          },
          "name": "",
          "term_id": "",
        },
        "TotalCount": 2
    }

let options = [];
for(let i=0; i<response.TotalCount; i  ) {
  options.push({key:response.Terminals[i].term_id, label: response.Terminals[i].name})
}

console.log(options)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using Object.values()

const data  = {
  "Status": "SUCCESS",
  "Terminals":  {
     "0":  {
        "name": "GENESIS- DEMO Terminal",
        "term_id": "GENESIS",
      },
      "1":  {
        "name": "GENESIS- DEMO Terminal",
        "term_id": "GENESIS",
      }
    },
    "TotalCount": 1
};
    
 const dropDownArray = Object.values(data.Terminals).map(({ name: label, term_id: key }) => ({ key, label }));
 console.log(dropDownArray);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related