Home > Software design >  Iterate through array of objects,not giving required output
Iterate through array of objects,not giving required output

Time:01-24

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

CodePudding user response:

Since it's an array, you have to get the index of the item (in this case the first item — index 0).

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"
    }
  ]
  
const trendingTopicsData = trendingTopics[0].data;
console.log(trendingTopicsData)

CodePudding user response:

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
})
  • Related