Home > Mobile >  How can I fetch one value type from the JSON data and display in a list?
How can I fetch one value type from the JSON data and display in a list?

Time:03-23

Firstly apologies as I am fairly new to fetching from an API and I am trying to learn.

I need to fetch all instances of the "number" from the "result" object and display in an unordered list or with a delimiter (see example JSON result below)

{
"code": "200",
"drawdate": "1 มีนาคม 2564",
"result": [
    {
        "id": "lotto_one",
        "name": "รางวัลที่ 1",
        "reword": 6000000,
        "amount": 1,
        "number": "835538"
    },
    {
        "id": "lotto_first_three",
        "name": "เลขหน้า 3 ตัว",
        "reword": 4000,
        "amount": 2,
        "number": [
            "290",
            "838"
        ]
    },
    {
        "id": "lotto_last_three",
        "name": "เลขท้าย 3 ตัว",
        "reword": 4000,
        "amount": 2,
        "number": [
            "051",
            "806"
        ]
    },
    {
        "id": "lotto_last_two",
        "name": "เลขท้าย 2 ตัว",
        "reword": 2000,
        "amount": 1,
        "number": "73"
    },
    {
        "id": "lotto_side_one",
        "name": "รางวัลข้างเคียงรางวัลที่ 1",
        "reword": 2000,
        "amount": 1,
        "number": [
            "835537",
            "835539"
        ]
    },
    {
        "id": "lotto_two",
        "name": "รางวัลที่ 2",
        "reword": 200000,
        "amount": 5,
        "number": [
            "316827",
            "731177",
            "743731",
            "788652",
            "923096"
        ]
    },

I have put together an example using the chucknorris api, using various tutorials, but It displays all data and categories.

How can I catch and display all result values only in a list with a delimiter such as this:

123456 | 012345 | 097749 | 039249 etc

const output = document.querySelector('.output');

fetch('https://api.chucknorris.io/jokes/random', { 
    headers: {
      "Content-Type": "application/json",
    "x-api-key": "pass",
    },
  })
  .then(response => response.json())
  .then(updateHTML);

function updateHTML(data) {

  // Get the object entries - and array of key/value pairs
  const entries = Object.entries(data);

  // Iterate over the entries and return a new array
  // of strings created from the key/value using a
  // template string.
  const rows = entries.map(([key, value]) => {
    return `
      <tr>
        <td >${key}</td>
        <td>${value}</td>
      </tr>
    `;
  });

  // Create a new HTML string by `join`ing up the row array
  // and adding it to a new string
  const html = `<table><tbody>${rows.join('')}</tbody></table>`;

  // Insert the HTML into the page
  output.insertAdjacentHTML('beforeend', html);
}
<div ></div>

CodePudding user response:

EDIT (based on comments): It appears you are going to fetch a REST endpoint, so you can not fetch only parts of a response (as opposed to e.g. graphQL) so all you can do is selectivelly include/exclude data that you need. I updated the code to reflect this.

The code is good but you should always try to code your app with data as close as possible to the real one. Using a data source with a different shape from what you will end up using will always bring in bugs and changes in code.

I updated your example to use the data you provided instead of fetching from the API you were using. Take a look into the nested loop in the updateHTML() method.

const src = {
"code": "200",
"drawdate": "1 มีนาคม 2564",
"result": [
{
    "id": "lotto_one",
    "name": "รางวัลที่ 1",
    "reword": 6000000,
    "amount": 1,
    "number": "835538"
},
{
    "id": "lotto_first_three",
    "name": "เลขหน้า 3 ตัว",
    "reword": 4000,
    "amount": 2,
    "number": [
        "290",
        "838"
    ]
},
{
    "id": "lotto_last_three",
    "name": "เลขท้าย 3 ตัว",
    "reword": 4000,
    "amount": 2,
    "number": [
        "051",
        "806"
    ]
},
{
    "id": "lotto_last_two",
    "name": "เลขท้าย 2 ตัว",
    "reword": 2000,
    "amount": 1,
    "number": "73"
},
{
    "id": "lotto_side_one",
    "name": "รางวัลข้างเคียงรางวัลที่ 1",
    "reword": 2000,
    "amount": 1,
    "number": [
        "835537",
        "835539"
    ]
},
{
    "id": "lotto_two",
    "name": "รางวัลที่ 2",
    "reword": 200000,
    "amount": 5,
    "number": [
        "316827",
        "731177",
        "743731",
        "788652",
        "923096"
    ]
},
  ]
};
const output = document.querySelector('.output');
/*
// Use local data instead
fetch('https://api.chucknorris.io/jokes/random', { 
    headers: {
      "Content-Type": "application/json",
    "x-api-key": "pass",
    },
  })
  .then(response => response.json())
  .then(updateHTML);
*/
function updateHTML(data) {

  // Get the object entries - and array of key/value pairs
  const entries = Object.entries(data);

  // Iterate over the entries and return a new array
  // of strings created from the key/value using a
  // template string.
  const rows = data.map((entry) => {
    return Object.keys(entry).map((key) => {
      let value = entry[key];
      if (key === 'number') {
        if (Array.isArray(value)) {
          value = value.join(' | ');
        }
        return `
          <tr>
            <td >${key}</td>
            <td>${value}</td>
          </tr>
        `;
      }
    }).join('');
    
  });

  // Create a new HTML string by `join`ing up the row array
  // and adding it to a new string
  const html = `<table><tbody>${rows.join('')}</tbody></table>`;

  // Insert the HTML into the page
  output.insertAdjacentHTML('beforeend', html);
}
updateHTML(src.result);
<div ></div>

  • Related