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

Transforming Image Annotation from Angular 1 to Angular 4: Overcoming Conversion Challenges and Comparing Equivalents from 1.x to 4

After exploring various options, I am still struggling to resolve the conversion error that occurs when trying to convert my Angular 1.x script for image annotation into Angular 4. The equivalent of angular 1.x code in Angular 4 is not readily available. H ...

Sharing Data Across Multiple Windows in Angular 2 Using a Singleton List

My multiplayer game involves adding new players to a single game room lobby, which is essentially a list of current players. How can I update this list for all connected players when new ones join? I implemented a service and included it in the providers ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

Passing an ID in Next.js without showing it in the URL

I am looking to transfer the product id from the category page to the product page without showing it in the URL Category.js <h2> <Link href={{ pathname: `/product/car/${title}`, query: { id: Item.id, }, }} as={`/p ...

Exploring the Differences Between Next.js Script Components and Regular Script Tags with async and defer Attributes

Can you explain the distinctions between the next js <Script /> component rendering strategies such as afterInteracive, beforeInteractive, and lazyLoad, as opposed to utilizing a standard <script /> tag with attributes like async and defer? ...

How do I convert a byte array from a JSON object in an Android

How can I extract byte[] from JSON using a web service? Here is the JSON format I have: [{"imgLogo":[255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,219,0,132,0, 9,6,7,20,19,18,20,20,19,20,21,22,20,22,20,21,24,22,21,21,20,20,20,20,20, ...

Encountering TypeError while attempting to assign an axios response to a data variable within a Vue component

Encountering the error message TypeError: Cannot set property 'randomWord' of undefined specifically at the line: this.randomWord = response.data.word; Confirming that console.log(response.data.word) does display a string. Vue Component Structu ...

What is the process for altering a designated element within a matrix to align with another matrix?

My current project involves creating a matrix 'B' that is derived from another matrix 'A'. Both matrices have the same size, and I aim to have every position in matrix 'B' reflect a 1 in the corresponding position of matrix &a ...

What is the best way to utilize getters and setters for an array variable in order to retrieve specific array items by index rather than the entire array as a whole?

class CustomClass { var storedDates: [Date] { get { return cloudKitRecord.object(forKey: "dates") as! [Date] } set(newDates) { cloudKitRecord.setObject(newDates as! CKRecordValue, "dates") ...

confrontation arising between two PHP scripts due to conflicting functionalities within the MetaSlider plugin

Seeking assistance with the WordPress plugin metaslider, specifically involving two code snippets. The first one implements the "ken burns effect" while the second disables the "pause on action" feature. Strangely, the "pause on action" seems to interfere ...

Applying the document height to window height ratio to create a scale ranging from 1 to 100

My goal is to create a scroll bar using two divs with heights of 110px and 10px. The smaller one will be nested inside the taller one, allowing for adjustment of its margin-height from 0 to 100px while still fitting within the larger div. When I refer to ...

What is the best way to reset an a-select component in Ant Design Vue?

I need to programmatically reset the selection in my a-select component after a specific event is triggered. Here's an example of my a-select code snippet: <a-select style="marginTop: 8px;width: 20%" @change="onChanged" > ...

retrieve the preferred item data from the local storage

Having trouble retrieving favorite items from my list item app using Ionic 4. Although my JSON data is added to local storage, I am unable to retrieve the data properly. favourite.service.ts getAllFavoriteItems(){ return this.storage.get("object"); ...

Creating various functions for Joomla's AJAX component development

My component is currently working smoothly with AJAX and mootools. The view.raw.php file contains only one function called display. I've been attempting to add other functions within the component that can be accessed through AJAX, but have been facin ...

Python allows for the creation of new arrays or variables without the need to predefine them beforehand

num = input('Enter a number: ') eval('List'+num)=[] I predicted it would be similar to this approach, but I encountered an error stating 'Can't assign to function call'. Any suggestions on how to fix this issue? If ther ...

What is preventing me from utilizing global variables in distinct HTML and JavaScript files?

I am facing a perplexing issue with my HTML files, specifically index.html and lobby.html. Within main.js, which is loaded in index.html, I attempt to load lobby.html using window.location.href. Despite trying various methods to define global variables i ...

What is the definition of the term "WebapiError"?

I'm currently developing a Spotify Web App that focuses on retrieving the top albums of KD Rusha using the Client ID and Artist ID to exclusively fetch his releases on Spotify. To accomplish this, I am utilizing an npm package called spotify-web-api-n ...

To complete Mocha tests, ensure to use the done() method. However, keep in mind that the resolution method is too specific. Choose either to specify a callback *or* return a Promise, but not both simultaneously

Encountering a frustrating issue with a mocha test. When I leave it alone, it freezes and displays: Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. If I include `Pro ...

Arranging Data in Arrays using Angular 4 GroupBy Feature

I'm working with an array structured like this: var data = [ { student: "sam", English: 80, Std: 8 }, { student: "sam", Maths: 80, Std: 8 }, { student: "john", English: 80, Std: 8 }, { student: "j ...

Is it possible for my website to send an email without the need for a script to be executed?

Looking to include a contact page on my website, but struggling with limitations imposed due to hosting on a secure school server that restricts script execution. Wondering if there's a workaround that would allow for email sending on the client side ...