Filtering deeply nested arrays

Hey, I'm working with this interesting array:

   [ {
        "Navn": "Long Island Iced Tea",
        "Nummer": "2",
        "Glas i ml": "250",
        "Instruktioner": "",
        "a": "Hæld is i glasset",
        "b": "pynt med en skive lime",
        "Ingredienser": [
            {
                "Type": "Spiritus",
                "Del1": [
                    {
                        "Cointreau": 20
                    }
                ],
                "Del2": [
                    {
                        "Gin": 20
                    }
                ],
                "Del3": [
                    {
                        "Rom_Lys": 20
                    }
                ],
                "Del4": [
                    {
                        "Tequila": 20
                    }
                ],
                "Del5": [
                    {
                        "Vodka": 20
                    }
                ]
            },
            {
                "Type": "Vand/Juice",
                "Del1": [
                    {
                        "Cola": 40
                    }
                ],
                "Del2": [
                    {
                        "Sprite": 20
                    }
                ]
            },
            {
                "Type": "Mixer",
                "Del1": [
                    {
                        "Lime_Sirup": 20
                    }
                ]
            }
        ]
    }]

This is specifically for a Cocktailmachine.

I'm trying to filter it by "Del1" and search for ingredients like "Rom_Lys," "Cola," and "Vodka" to create a new array with these specific items.

I've looked around different resources but haven't found a solution yet. Experimented with filters and includes, but no luck so far.

Thank you for any help!

Answer №1

To find items that contain the word Cola, you can utilize the filter and some methods:

const filterWord = 'Cola';

const result = sampleData.filter(s => 
    s.Ingredienser.some(s => 
        s.Del1.some( e=> e[filterWord])));

console.log(result);

For example:

let sampleData = [
{
    "Navn": "Rom & Cola/ Cuba Libre",
    "Nummer": "0",
    "Glas i ml": "200",
    "Instruktioner": "",
    "a": "Hæld is i glasset",
    "b": "pynt med en skive citron",
    "Ingredienser": [
        {
            "Type": "Spiritus",
            "Del1": [
                {
                    "Rom_Lys": 40
                }
            ]
        },
        {
            "Type": "Vand/Juice",
            "Del1": [
                {
                    "Cola": 100
                }
            ]
        },
        {
            "Type": "Mixer",
            "Del1": [
                {}
            ]
        }
    ]
},
{
    "Navn": "Isbjørn",
    "Nummer": "1",
    "Glas i ml": "200",
    "Instruktioner": "",
    "a": "Hæld is i glasset",
    "b": "pynt med en skive citron",
    "Ingredienser": [
        {
            "Type": "Spiritus",
            "Del1": [
                {
                    "Vodka": 30
                }
            ]
        },
        {
            "Type": "Vand/Juice",
            "Del1": [
                {
                    "Sprite": 60
                }
            ]
        },
        {
            "Type": "Mixer",
            "Del1": [
                {
                    "Blå_Sirup": 30
                }
            ]
        }
    ]
}];


const filterWord = 'Cola';
const result = sampleData.filter(s => s.Ingredienser.some(s => s.Del1.some( e=> e[filterWord])));
console.log(result);

UPDATE:

If you need to check for multiple keys, you can use the hasOwnProperty method to determine if the object contains a specific key:

const filters = ['Cointreau', 'Gin', 'Rom_Lys'];
const result = sampleData.filter(s =>
    s.Ingredienser.some(ingred => {
        return Object.keys(ingred).some(k=> {
            if (Array.isArray(ingred[k])) {
                return ingred[k].some(s=> filters.some(f=> {
                    return s.hasOwnProperty(f);
                }))
            }
        });
    }
));

Here's an example:

let sampleData = [ {
"Navn": "Long Island Iced Tea",
"Nummer": "2",
"Glas i ml": "250",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive lime",
"Ingredienser": [
    {
        "Type": "Spiritus",
        "Del1": [
            {
                "Cointreau": 20
            }
        ],
        "Del2": [
            {
                "Gin": 20
            }
        ],
        "Del3": [
            {
                "Rom_Lys": 20
            }
        ],
        "Del4": [
            {
                "Tequila": 20
            }
        ],
        "Del5": [
            {
                "Vodka": 20
            }
        ]
    },
    {
        "Type": "Vand/Juice",
        "Del1": [
            {
                "Cola": 40
            }
        ],
        "Del2": [
            {
                "Sprite": 20
            }
        ]
    },
    {
        "Type": "Mixer",
        "Del1": [
            {
                "Lime_Sirup": 20
            }
        ]
    }
]
}];

const filters = ['Cointreau', 'Gin', 'Rom_Lys'];
const result = sampleData.filter(s =>
s.Ingredienser.some(ingred => {
    return Object.keys(ingred).some(k=> {
        if (Array.isArray(ingred[k])) {
            return ingred[k].some(s=> filters.some(f=> {
                return s.hasOwnProperty(f);
            }))
        }
    });
}
));
console.log(result);

Answer №2

Consider utilizing the code snippet below to effectively filter the array.

let filteredArray = myArray.filter(function(item) {
    for (let i = 0; i < item.ingredients.length; i++) {
        if (item.ingredients[i].Category1[0].hasKey(selectedOption)) {
            return true;
        }
    }
    return false;
});

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

What are the steps to integrate and utilize DefinePlugin within your webpack configuration?

Hello, I'm currently trying to implement the DefinePlugin in order to update the version number and ensure that my JavaScript refreshes after a new build is released. Unfortunately, I am encountering issues with getting DefinePlugin to work properly. ...

Error encountered while scrolling with a fixed position

I am currently in the process of developing a carousel slider that resembles what we see on Android devices. The main challenge I am facing at this early stage is applying the CSS property position: fixed; only horizontally, as vertical scrolling will be n ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

"Troubleshooting a callback problem in jQuery involving JavaScript and AJAX

UPDATE3 and FINAL: The problem has been resolved with the help of Evan and meder! UPDATE2: To clarify, I need the existing function updateFilters(a,b) to be called, not created. My apologies for any confusion. The issue with the code below is that udpate ...

A guide to replacing or customizing standard components in ReactJS

I need to modify the color property of a common component so I can use it elsewhere. const ViewAllIcon = (props) => ( <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 26 ...

The AbortController feature does not initiate the cancellation of an axios.get request

Currently, I'm experimenting with utilizing AbortController to cancel an API call. The axios library is being used for this particular call. Before integrating it into my project, I decided to test the cancellation procedure with a simple call: const ...

Perform validation on input by monitoring checkbox changes in Angular 4

I am currently working on a project where I need to loop through an array of key values in order to create a list of checkboxes, each accompanied by a disabled input field as a sibling. The requirement is that upon checking a checkbox, the corresponding in ...

Utilize dynamic global variables in React that are provided during runtime, making them unpredictable during the build process

I am currently developing an application for Overwolf, which you can find more information about at For this platform, applications are built using html/js and run in the Overwolf Browser. The browser provides access to the Overwolf API through a global v ...

The browser is opting to download the HTML file rather than displaying it

Recently, I set up a server using Node.JS express where I specified the location of an HTML file in the public folder. app.use(express.static(__dirname + '/public')); app.listen(8080); In previous projects, this setup worked seamlessly. However ...

The pagination feature for Swiper is experiencing issues across both desktop and mobile platforms

I am having an issue with the pagination display in the text. I would like it to appear below the text as a standalone item for better visibility. Another problem arises when viewing the page on mobile devices - the hamburger menu displays behind the slid ...

Is there a way to incorporate the MUI theme color into inline styles?

Imagine I have the following tabs displayed below. Is there a way to implement MUI's primary and secondary colors for inline CSS? My goal is to personalize the colors using my own palette. <Tabs value={value} ...

Ways to retrieve the output parameter in the node mssql

` request.input('xyz',sql.Int,1); request.input('abc',sql.Numeric,2); request.output('pqr',sql.Int); request.output('def',sql.Char); request.execute('[StoredProcedure]',function(err,recor ...

Traversing through stdClass objects and arrays in PHP

Hey there, I'm currently using the WooCommerce REST API to retrieve order information from a WooCommerce website. The data is returned in JSON format, and I am able to access all of the data using the following loop: $orders = $connect->orders-&g ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...

Error encountered when running the production build server for android in Meteor: TypeError - Unable to access property 'slice' of null

Here's a demo I'm working on: https://github.com/pc-magas/pupAndroidDemo I'm trying to build this demo for Android. I've already installed the Android SDK and configured the necessary environmental parameters. Following the instructio ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

TinyMCE is substituting the characters "<" with "&lt;" in the text

I am currently using Django with placeholder tags: I am attempting to insert a flash video into my TinyMCE editor, but it is replacing the '<' symbol with < in the code, preventing it from loading properly and only displaying the code. I hav ...

Utilize DataTables with a custom search form for enhanced data filtering

I rely on DataTables for its advanced functionality in creating tables with paging capabilities. When submitting data through a standard jQuery Ajax request using my own form, the returned data is formatted and then passed to the DataTables function to en ...

Create a spinner control on an HTML webpage with the help of JavaScript

I am attempting to create a spinner control on my webpage, and I have tried the following code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.o ...

Tap to reveal additional information with the power of Jquery and ajax

I have a question regarding the popup slide functionality. I would like to achieve the following: Currently, I am using the following code to display post details upon clicking: function getPostDetails(id){ var infoBox = document.getElementById("in ...