skip to Main Content

given code

    [
      {
        "data": [
          {
            "text_name": "test",
            "text_url": "https://www.news18.com/topics/gold-prices/1",
            "is_new": "1"
          },
          {
            "text_name": "test2",
            "text_url": "https://www.news18.com/topics/gold-prices/2",
            "is_new": "0"
          }
        ],
        "slug": "bollywood",
        "heading": "testing",
        "status": "1",
        "is_open_new": "1",
        "order_data": "2",
        "section_dropdown": "bollywood"
      }
    ]

I want to iterate through this given code snippet and get the data.

const trendingTopicsData = trendingTopics.data

but this is showing null

2

Answers


  1. Since the object in the snippet is an array, first you have to get the index of the item you want to work with (in this case the first item — index 0). Then you can iterate through the data array however you want (loop, forEach, map etc.).

    Try:

    const trendingTopicsData = trendingTopics[0].data
    

    Here it is as a runnable snippet:

    const trendingTopics = [
        {
          "data": [
            {
              "text_name": "test",
              "text_url": "https://www.news18.com/topics/gold-prices/1",
              "is_new": "1"
            },
            {
              "text_name": "test2",
              "text_url": "https://www.news18.com/topics/gold-prices/2",
              "is_new": "0"
            }
          ],
          "slug": "bollywood",
          "heading": "testing",
          "status": "1",
          "is_open_new": "1",
          "order_data": "2",
          "section_dropdown": "bollywood"
        }
      ]
    
    // Get trending topics data array
    const trendingTopicsData = trendingTopics[0].data;
    console.log("Data array:", trendingTopicsData)
    
    // Iterate through each of the items in the data array
    trendingTopicsData.forEach((dataItem, index) => console.log(`Data item #${index}:`, dataItem));
    Login or Signup to reply.
  2. The object you are trying to access is inside an array. You will have to loop through the array

    trendingTopics.forEach(topic => {
      // do something with topic.data
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search