Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter object by name with JavaScript

I made a request to an endpoint and I get this object, I’m filtering the name like this:

fetch('http://endpoint', requestOptions)
.then((response) => response.json())
.then((result) => {
  const onlineUsers = result.resource.items[1].onlineUsers >= 1;
  console.log(onlineUsers);
})
.catch((error) => console.log('error', error));

This workers, but I just need the result of what is in the key named Forms, but there is a possibility that it will change its position, so the items[1] it may not work anymore

This is an example of the object I receive:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "type": "application/vn+json",
  "resource": {
    "total": 4,
    "itemType": "application",
    "items": [
      {
        "name": "Test",
        "onlineUsers": 1
      },
      {
        "name": "Forms",
        "onlineUsers": 1
      },
      {
        "name": "Users",
        "onlineUsers": 7
      },
      {
        "name": "OnlineUsers",
        "onlineUsers": 5
      }
    ]
  },
  "method": "get",
  "status": "success"
}

Is there any way to receive this object and filter by name? Like:

if (hasName === "Forms", get onlineUsers) { 
  // Do something
}

Thanks!

>Solution :

As suggested in your question, you can use filter on your array. Something like that:

console.log(
  result.resource.items.filter((item) => item.name === "Forms")
);

This will print an array with all items having the name Forms. Using your example:

[
  {
    "name": "Forms",
    "onlineUsers": 1
  }
]

If there is only one item with the name Forms, or if you want only the first one, find may be a good alternative with a similar syntax:

console.log(
  result.resource.items.find((item) => item.name === "Forms")
);

This will only print the first found object (or null if none is matching), without the array "pollution":

{
  "name": "Forms",
  "onlineUsers": 1
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading