Search code examples
javascriptarraysjsonobject

Iterate through array of objects,not giving required output


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


Solution

  • 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));