Browsing through json subgroups

Having issues with filtering an array within my JSON file.

Filtering the main array works fine, but I'm struggling to filter subarrays.

This is the structure of my JSON file:

[
    {
        "id": 1354,
        "name": "name",
        "type": "simple",
        "status": "ok",
        "categories": [
            {
                "id": 79,
                "name": "A",
            },
            {
                "id": 68,
                "name": "B",
            }
        ]
    },
    {
        "id": 1368,
        "name": "name",
        "type": "simple",
        "status": "ok",
        "categories": [
            {
                "id": 79,
                "name": "A",
            },
            {
                "id": 72,
                "name": "C",
            }
        ]
    },
    {...}
]

The current code successfully filters and returns items with status: 'ok':

return items.filter( item => {
    return item.status == 'ok';
});

However, I'm looking to filter and return items with category.name: 'B'.

The code I have only seems to work with the first category, not considering subsequent categories:

return items.filter( item => {
    for (let category of item.categories) {
        return category.name == 'B';
    }
});

Open to any suggestions or ideas, thank you.

Answer №1

Consider utilizing Array.prototype.some() instead - it will return true only if a condition is met by some of the array elements.

const data = [
    {
        "id": 1354,
        "name": "name",
        "type": "simple",
        "status": "ok",
        "categories": [
            {
                "id": 79,
                "name": "A",
            },
            {
                "id": 68,
                "name": "B",
            }
        ]
    },
    {
        "id": 1368,
        "name": "name",
        "type": "simple",
        "status": "ok",
        "categories": [
            {
                "id": 79,
                "name": "A",
            },
            {
                "id": 72,
                "name": "C",
            }
        ]
    },
    {
        "id": 1364,
        "name": "name",
        "type": "simple",
        "status": "ok",
        "categories": [
            {
                "id": 71,
                "name": "B",
            },
            {
                "id": 70,
                "name": "C",
            }
        ]
    },
]

const result = data.filter(firstLevel => {
  return firstLevel.categories.some(secondLevel => secondLevel['name'] === 'B')
})

console.log(result);

Answer №2

You seem to be exiting your for loop too soon. Consider using some method instead:

const result = array.filter(item => item.categories.some(({name}) => name === 'B'));
console.log(result);
<script>
const array = [
    {
        "id": 1354,
        "name": "name",
        "type": "simple",
        "status": "ok",
        "categories": [
            {
                "id": 79,
                "name": "A",
            },
            {
                "id": 68,
                "name": "B",
            }
        ]
    },
    {
        "id": 1368,
        "name": "name",
        "type": "simple",
        "status": "ok",
        "categories": [
            {
                "id": 79,
                "name": "A",
            },
            {
                "id": 72,
                "name": "C",
            }
        ]
    },

]
</script>

Answer №3

Upon completing the initial category check, you have come back. To proceed with the iteration, make sure that the category name does not match the specified pattern. Only return false when all iterations have been completed.

return items.filter(item => {
    for (let category of item.categories) {
      if (category.name === 'B') {
        return true;
      }
    }
    return false;
});

Answer №4

If you want to filter items based on a specific category, you can use the following code snippet:

const filteredItems = items.filter(item => {
    return item.categories.findIndex(category => category.name === 'B') > -1;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a preview image for a three.js environment

I am currently working on a website dedicated to visualizing the biological neurons found in animals. I have a comprehensive list of neuron names, and I use THREE JS to draw the neuron when the user clicks on its name. However, with hundreds of neurons to ...

The scroll-to-top arrow remains concealed when the height of the html and body elements is set to 100

I recently added a scroll-to-top arrow using Jquery, and it's functioning flawlessly. However, I encountered an issue when I set body and html to a height of 100%, as it mysteriously disappears. View this fiddle for reference The HTML structure is a ...

What's the best way to neatly display an array of objects with two values using JSON?

My JSON data is structured like this: "members": [ "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e2e7eeeaedc3f7e6f0f7ade0ecee">[email protected]</a>", "<a href="/cdn-cgi/l/email-pr ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...

What is the best way to integrate ReCaptcha into a Nextjs contact form?

Currently, I am in the process of designing a portfolio website that includes a contact form for visitors to get in touch with me. I have successfully integrated SendGrid for email transfer, but my main concern now is spam. Despite my efforts to find a sol ...

Tips for generating a fresh array by conditionally including an extra property based on the comparison of two arrays

I am working with two different arrays: lockers: [ { locker_id: 1, label: { size: 1, label: "small" } }, { locker_id: 2, label: { size: 3, label: "medium" } }, { locker_id: 3 ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

I attempted to verify the login through postman, but encountered an error in the process

I created the login route on the backend and tested it in Postman, but encountered this error message: https://i.stack.imgur.com/PdyCo.png Below is the code for the login route: router.post("/login", async (req, res) => { try { const user = await ...

Error: The function updateElement does not exist

Currently, I am facing an issue while trying to update an element in an array by adding an object as a property. This requires user interaction through a modal where the form is filled and then added as a property for a specific node. However, I encountere ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

This as well as its parent node

I am looking to implement a function where an element is manipulated if a child of it is clicked (by adding a CSS class to it). My current approach is as follows: function mahlzeitRaus() { console.log("Out"); //this.className += " not"; this. ...

Tips for modifying style.display using JavaScript

On my website, the menu is structured like this: <nav id="menu"> <label for="tm" id="toggle-menu">Menu <span class="drop-icon">▾</span></label> <input type="checkbo ...

Struggling to convert integer value into a byte array

Let's explore the concept of a union in programming. A union is defined as a data structure that holds different variables in the same memory location, allowing you to access them using different variable types. In this particular case, we are given a ...

Multiplying Python arrays with different lengths

My task involves multiplying arrays that are uneven in this case, and my goal is to preserve the 7 and the 10 in the result. import numpy as np matrix = np.array([[1,2],[3,4]]) customArray = np.array([[5,6,7],[8,9,10]]) result = matrix * customArray #Exp ...

What could be causing my recursive function to skip over certain parts of my JSON data?

UPDATED TO BE MORE CONCISE Hello, I'm looking for assistance with a recursive function that's not returning the expected values from a JSON object. The goal is to retrieve all "Flow" object IDs where the "Type" is either "Standard" or "Block". T ...

The initial page in jqgrid may show rowobject value as undefined, but subsequent pages will display the correct rowObject values

While working with jqgrid-4.8, I encountered an issue where the rowObject value is coming up as undefined in the first page but values are received in subsequent pages when using rowObject.name. However, if rowObject[0] is used, the values of rowObject are ...

What is the best way to generate a static header in nextJS?

I am looking to create a static navbar without needing client-side fetching. Currently, I am using Apollo GraphQL and my _app.js file is set up like this: import React from 'react'; import Head from 'next/head'; import { ApolloProvider ...

Can a before hook ever run after a test in any situation, Mocha?

My before hook runs after the initial test and at the conclusion of the second test. Here is the code for my before hook: before(function () { insightFacade.addDataset("courses", content) .then(function (result: InsightResponse) { ...

Tips for showing solely the current page number within angular pagination

HTML : <!-- pagination controls --> <div class="pagination-container"> <pagination-controls (pageChange)="onPageChange($event)" [maxSize]="1" [id]="config.id" [directionLinks]="true">< ...

Implementing a node.js application deployment with pm2 to ensure zero downtime

While there are countless tutorials on developing chat applications using socket.io and node.js, the event-driven advantage of Node is undeniable for building chat apps. However, a recent thought crossed my mind - how can I ensure the sustainability of my ...