-2

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

shrys
  • 5,860
  • 2
  • 21
  • 36
navdhiman
  • 1
  • 3
  • 1
    Does this answer your question? [How to loop through an array containing objects and access their properties](https://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties) – shrys Jan 24 '23 at 12:29
  • 2
    `trendingTopics[0].data;` – Chris G Jan 24 '23 at 12:30

2 Answers2

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));
João Pesce
  • 2,424
  • 1
  • 24
  • 26
  • @navdhiman ... The OP'S own question was ... _**"Iterate through array of objects [...]"**_ and not _"How to access the sole first item of an array?"_ – Peter Seliger Jan 24 '23 at 14:08
1

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
})
Aaron Dev
  • 51
  • 2
  • @navdhiman ... The above answer provides a solution to what the OP actually did ask for ... _**"Iterate through array of objects [...]"**_ . – Peter Seliger Jan 24 '23 at 14:09