How to filter a json file to create a new array under a variable?

This is the code:

const theData = require(“./thejsons/data.json”);
const dataFilter = theData.filter((item) => item.data.id);

the error:

TypeError: theData.filter is not a function

What??.. I am trying to just extract the data.id for all of the items in the json file, and create a new variable that would hold an array of just the Id’s… How can I do that?

How the json looks like?

{
  "data": [
    {
      "author_id": "4895802969",
      "text": "Hello there!",
      "id": "1691209718214131712"
    },
    {
      "author_id": "927706966490845186",
      "text": "nothing much",
      "id": "1691208744846139393"
    },
    {
      "author_id": "1159445685156155393",
      "text": "its Friday!",
      "id": "1691199264335310850"
    }
  ]
}

Oh… its because .filter is for arrays, and the json is an object and it isn’t working very welll…

Gotta find a different way to do this…

Yes, I am slow…

Didn’t understand what you said… and I found the solution matching EXACTLY what you said…

the map() method didn’t work on theData object, but it DID work from theData.id

Here is the code:

const theData = require(“./thejsons/data.json”);

const dataMain = theData.data;

const theIds = dataMain.map((element) => element.id);

console.log(theIds);

I find it interesting that I couldn’t find a way to just work from the initial JSON object without having to make another variable pin pointing the array I was looking for… exploring all the other object methods such as keys, values, entries, it seems like non of those methods could reach the nested objects from my JSON file… anyway…

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.