Troubleshooting Issue with Filtering Nested Object Array Based on Property

At the core of my data structure lies an array of orders, each containing an array of line items. These line items, in turn, are associated with their respective categories. I am currently attempting to filter the order array based on the category ID of the line item, but I've hit a snag. While I managed something similar for filtering by item, it seems that delving into the third layer is proving problematic. My goal is to circumvent excessive loop iterations in this process.

The array in question is as follows:

[
{
    "href": "https://sandbox.dev.clover.com/v3/merchants/6RD8H04A896K1/orders/937K8W59RPEHW",
    ...
},
{
    "href": "https://sandbox.dev.clover.com/v3/merchants/6RD8H04A896K1/orders/3T3YN416MASV2",
    ...
}]

The specific category I aim to filter by is:

{id: "55DYZ8T2ZVB88", name:"Bowl"}

My current filtering implementation is outlined below:

this.orders.filter((order) => order.lineItems.some(lineItem => lineItem.categories.some(category =>category.id === item.id)));

However, despite the existence of nested arrays in the provided data, the filtration process fails and leads to the following error during debugging:

VM67561:1 Uncaught TypeError: Cannot read properties of undefined (reading 'some')

It appears that there might be a missing link or a different approach needed to resolve this issue effectively.

Prior to this, I successfully filtered by item ID, which functioned correctly. The code snippet for filtering by item ID was as follows:

this.orders.filter((order) => order.lineItems.some(lineItem =>lineItem.item.id === item.id));

Answer №1

const orders = [
{
    "href": "https://sandbox.dev.clover.com/v3/merchants/6RD8H04A896K1/orders/937K8W59RPEHW",
    "id": "937K8W59RPEHW",
    "currency": "USD",
    "employee": {
        "id": "VH7JB40JRGCAG"
    },
    "total": 1165,
    "paymentState": "OPEN",
    "title": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c4c6cdc6d1c2cfe3c7d0+uniqueID">[email protected]</a> safs",
    "orderType": {
        "id": "YT62H0SSGJF0M"
    },
    "taxRemoved": false,
    "isVat": false,
    "state": "open",
    "manualTransaction": false,
    "groupLineItems": false,
    "testMode": false,
    "createdTime": 1702095585000,
    "clientCreatedTime": 1702095585000,
    "modifiedTime": 1702095597000,
    "lineItems": [
        {
            "id": "F7W4DXKZNA4NP",
            "orderRef": {
                "id": "937K8W59RPEHW"
            },
            "item": {
                "id": "A5JPMS665CQW6"
            },
            "name": "Chicken Supreme Bowl /G,O With Bread",
            "alternateName": "",
            "price": 1099,
            "itemCode": "",
            "note": "",
            "printed": false,
            "createdTime": 1702095585000,
            "orderClientCreatedTime": 1702095585000,
            "exchanged": false,
            "refunded": false,
            "isRevenue": true,
            "categories": [
                {
                    "id": "55DYZ8T2ZVB88",
                    "name": "Bowl",
                    "sortOrder": 20,
                    "deleted": false
                }
            ]
        }
    ]
},
{
    "href": "https://sandbox.dev.clover.com/v3/merchants/6RD8H04A896K1/orders/3T3YN416MASV2",
    "id": "3T3YN416MASV2",
    "currency": "USD",
    "employee": {
        "id": "VH7JB40JRGCAG"
    },
    "total": 4025,
    "paymentState": "OPEN",
    "title": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f89f9d969d8a9994b89c8b8bd69b9795">[email protected]</a> gsrw",
    "orderType": {
        "id": "YT62H0SSGJF0M"
    },
    "taxRemoved": false,
    "isVat": false,
    "state": "open",
    "manualTransaction": false,
    "groupLineItems": false,
    "testMode": false,
    "createdTime": 1702095600000,
    "clientCreatedTime": 1702095600000,
    "modifiedTime": 1702095611000,
    "lineItems": [
        {
            "id": "AJWXHE6JE2W4T",
            "orderRef": {
                "id": "3T3YN416MASV2"
            },
            "item": {
                "id": "VNRDHNRBG5AVM"
            },
            "name": "Baklava 1 Tray",
            "alternateName": "",
            "price": 1499,
            "itemCode": "",
            "note": "",
            "printed": false,
            "createdTime": 1702095600000,
            "orderClientCreatedTime": 1702095600000,
            "exchanged": false,
            "refunded": false,
            "isRevenue": true,
            "categories": [
                {
                    "id": "TB58V8F5HTGYM",
                    "name": "DESSERTS",
                    "sortOrder": 15,
                    "deleted": false
                }
            ]
        },
        {
            "id": "F4VYPXC1X9J1J",
            "orderRef": {
                "id": "3T3YN416MASV2"
            },
            "item": {
                "id": "QXBQAMMZR8M6T"
            },
            "name": "Veggie Fried Rice",
            "alternateName": "",
            "price": 1199,
            "itemCode": "",
            "note": "",
            "printed": true,
            "createdTime": 1702095600000,
            "orderClientCreatedTime": 1702095600000,
            "exchanged": false,
            "refunded": false,
            "isRevenue": true,
            "categories": [
                {
                    "id": "F4HYDJAKE13K0",
                    "name": "FRIED RICE",
                    "sortOrder": 13,
                    "deleted": false
                }
            ]
        },
        {
            "id": "ZAECC4E18MB5T",
            "orderRef": {
                "id": "3T3YN416MASV2"
            },
            "item": {
                "id": "A5JPMS665CQW6"
            },
            "name": "Chicken Supreme Bowl /G,O With Bread",
            "alternateName": "",
            "price": 1099,
            "itemCode": "",
            "note": "grgre",
            "printed": false,
            "createdTime": 1702095600000,
            "orderClientCreatedTime": 1702095600000,
            "exchanged": false,
            "refunded": false,
            "isRevenue": true,
            "categories": [
                {
                    "id": "55DYZ8T2ZVB88",
                    "name": "Bowl",
                    "sortOrder": 20,
                    "deleted": false
                }
            ]
        }
    ]
}]


let desiredCategory = { id: "55DYZ8T2ZVB88", name: "Bowl" }; object to filter

let filteredOrders = orders.filter(order => {
  return order.lineItems.some(lineItem => 
    lineItem.categories.some(category =>
      category.id === desiredCategory.id && category.name === desiredCategory.name
    )
  );
});

console.log(filteredOrders);

Answer №2

It seems like you're making progress in the right direction. To finish your code, follow these steps:

const 
      orders = [ { "href": "https://sandbox.dev.clover.com/v3/merchants/6RD8H04A896K1/orders/937K8W59RPEHW", "id": "937K8W59RPEHW", "currency": "USD", "employee": { "id": "VH7JB40JRGCAG" }, "total": 1165, "paymentState": "OPEN", "title": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b1c1e151e091a173b1f080855181416">[email protected]</a> safs", "orderType": { "id": "YT62H0SSGJF0M" }, "taxRemoved": false, "isVat": false, "state": "open", "manualTransaction": false, "groupLineItems": false, "testMode": false, "createdTime": 1702095585000, "clientCreatedTime": 1702095585000, "modifiedTime": 1702095597000, "lineItems": [ { "id": "F7W4DXKZNA4NP", "orderRef": { "id": "937K8W59RPEHW" }, "item": { "id": "A5JPMS665CQW6" }, "name": "Chicken Supreme Bowl /G,O With Bread", "alternateName": "", "price": 1099, "itemCode": "", "note": "", "printed": false, "createdTime": 1702095585000, "orderClientCreatedTime": 1702095585000, "exchanged": false, "refunded": false, "isRevenue": true, "categories": [ { "id": "55DYZ8T2ZVB88", "name": "Bowl", "sortOrder": 20, "deleted": false } ] } ] }, { "href": "https://sandbox.dev.clover.com/v3/merchants/6RD8H04A896K1/orders/3T3YN416MASV2", "id": "3T3YN416MASV2", "currency": "USD", "employee": { "id": "VH7JB40JRGCAG" }, "total": 4025, "paymentState": "OPEN", "title": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b2b0bb...)
      
      filterBy = {id: "55DYZ8T2ZVB88", name:"Bowl"},
      
      fOrders = orders.filter(
          ({lineItems:li}) => li.some(({categories:ca}) => ca.some(
              ({id,name}) => id === filterBy.id && name === filterBy.name
          ))
      );
      
console.log( fOrders );

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

Enhance Your Search Functionality with an Angular Pipe

I created a custom pipe that filters the search field and displays a list of items based on the search text. Currently, it only filters by companyDisplay, but I want to also filter by companyCode and companyName. JSON [{ companyDisplay: "ABC", co ...

Remove the export statement after transpiling TypeScript to JavaScript

I am new to using TypeScript. I have a project with Knockout TS, and after compiling it (using the Intellij plugin to automatically compile ts to js), this is my sample.ts file: import * as ko from "knockout"; ko; class HelloViewModel { language: Kn ...

Enhancing the tooltip inner content in Bootstrap with a description:

Can you help me troubleshoot the code below? I am trying to add a description to numbers in my tooltip, but it doesn't seem to be working. Here is the HTML: <input id="contract-length" class="slider slider-step-2 slider-contract-length" ...

Refreshing the page after making an API call does not result in updated data

Within my VueJS application, I have implemented an API call to retrieve user statistics for display. The process involves a straightforward Java backend and utilizing an $axios get request. Upon initial page load, everything functions as anticipated. Howev ...

Guide to sorting a 2D array using pointers

I have created a code to sort an array of pointers, where the first element in the array indicates how many elements will follow after it. Now, I want the code to sort each line independently while retaining the first element (which signifies the size of ...

incorrect encoding of Greek characters due to the multer upload package

When uploading files with Greek characters, the uploaded titles are saved as ΠÏξ Îαξ & ÎαÏÏιμιÏαίοι Here is the code for multer variables inside a js file: const storage = multer.diskStorage({ destination: f ...

Combine several elements in a single jQuery scrollreveal function

I am currently working on a webpage that utilizes the jQuery library plugin scrollreveal to gradually reveal different html elements when the page loads. The functionality of the code is working correctly at the moment, but I have noticed that there is a d ...

Refresh the webpage content by making multiple Ajax requests that rely on the responses from the previous requests

I am facing a challenge where I need to dynamically update the content of a webpage with data fetched from external PHP scripts in a specific sequence. The webpage contains multiple divs where I intend to display data retrieved through a PHP script called ...

The functionality of if and else statements within local storage is not functioning as

I've been working on implementing a styleswitcher for my website. I successfully created a dropdown menu and saved it in localstorage. However, I'm facing an issue when trying to use the localstorage information to trigger an alert() through if a ...

The Word Document is unable to locate the module or its associated type declarations

Encountering an issue while attempting to import a file from the src/assets/documents directory. Currently working on a React Project using Typescript. The goal is to import a file and use its value within an anchor tag for downloading purposes. Interest ...

Tips for patiently anticipating the outcome of asynchronous procedures?

I have the given code snippet: async function seedDb() { let users: Array<Users> = [ ... ]; applications.map(async (user) => await prisma.user.upsert( { create: user, update: {}, where: { id: user.id } })); } async function main() { aw ...

What is the best way to determine the type of `rootReducer`?

My project is set up with a combination of React, Redux, Immutable.js, and TypeScript. As I worked on implementing it, I made an effort to declare types wherever possible which led me to discover an interesting issue. A code example illustrating the proble ...

Automatically reloading POST request when browser back button is pressed

Our web application is built on Spring MVC and Thymeleaf. When a user lands on the home page with a GET request, they enter 2 parameters and submit a POST request. After successful submission, they are directed to another page (let's call it page2) wi ...

How can you limit access to certain routes in Nuxt.js to only clients who possess a valid JWT token?

In Nuxt.js, implementing authentication can be done in the following steps: The client authenticates by sending its credentials in an HTTP request to a specific API route in the Nuxt backend; The Nuxt backend responds with a JWT token for accessing protec ...

Safely transmitting client-side encrypted information between individuals

I am developing a service that will keep personal information about a specific user, which should only be accessible by the author and the intended recipient. I want to encrypt the data on the client-side and store the encrypted version on the server. Res ...

What is the process for configuring vue.config.js with typescript?

Just starting out with typescript and running into an issue while configuring vue.config.js const webpack = require("webpack"); module.exports = { plugins: [ new webpack.DefinePlugin({ __VUE_I18N_FULL_INSTALL__: true, __ ...

Keeping an HTML field constantly refreshed with dynamic content from Django

Imagine having two input fields along with an HTML paragraph displaying a Django value. Field A: <input ...> Field B: <input ...> <p>{{ sum }}</p> The goal is to have the sum update in real time, meaning that once both numbers ...

Discovering a random element within a PHP array

A challenging task is before me as I examine the array and its var_dump result: array 6 => int 7 7 => int 8 9 => int 10 11 => int 12 Intriguingly, I aim to extract a random number from this array using $avil=array_r ...

What could be causing the sorting function to malfunction on certain columns?

My table's column sorting feature works well with first name and last name, but it seems to have issues with dl and dl score columns. I need assistance in fixing this problem. To access the code, click here: https://stackblitz.com/edit/angular-ivy-87 ...

Determining the offsetWidth and scrollWidth for option elements within a select field containing the multiple attribute on Internet Explorer 11

My select input element has multiple attributes and a fixed width set. Unfortunately, due to the fixed width, the overflowing content in the x-direction is not visible. To address this issue, I have created a JavaScript function that uses the title attribu ...