Is there a way to confirm and tally the occurrence of certain data within an associative array?

Seeking guidance on manipulating data within an associative array.

My Objective

I am looking to confirm the existence of an order in the sellingItems list.

Background Information

The goal is to determine if an order exists so that we can provide the current inventory count as a response.

The Query

I need to validate the presence of specific data (order) in an associative array and compute the stock quantity.

  public calculateStockQuantity(itemInstances) {
    const stockQuantity = //We want to count the number of items in stock. In this case, we want it to be 2 (calculated based on whether the data exists in sellingItem.order or not).)
   return stockQuantity;
  }

List of Targeted Associative Arrays

//There are three itemInstances for one product because the number of products sold is three.

itemInstances =
[
    {
        "id": "1",
        "sellingItem": [
            {
                "id": 1,
                "price": 3000,
                "orderedItem": [
                    {
                        "id": 1
                "ordered_at": "2021-04-01 10:00:00"
                    }
                ]
            }
        ]
    },
    {
        "id": "2",
        "sellingItem": [
            {
                "id": 2,
                "price": 3000,
                "orderedItem": []
            }
        ]
    },
    {
        "id": "2",
        "sellingItem": [
            {
                "id"": 2,
                "price": 3000,
                "orderedItem": []
            }
        ]
    }
]

Please excuse my amateurish query.

Answer №1

Kindly ascertain if this aligns with your requirements, assuming that in the case of an empty orderedItem array, a sellingItem will be considered as in stock.

let count = itemInstances.filter(({sellingItem : [{ orderedItem }]}) => orderedItem.length === 0).length;

console.log(count); //the result is expected to be 2 based on the information provided

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

Unable to show JSON data on the console

I am attempting to retrieve a large array of JSON objects from a remote server. The server-side is based on Node.js + redis. Here is my ajax query: $.ajax({ crossDomain: true, type:"GET", contentType: "application/json", url: "http://****. ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

Deciphering JSON Array in Swift

Is there a better way to parse a JSON array in string format using Swift without manually removing brackets and splitting by commas? The current algorithm fails if any array elements contain commas, like in the case of ("DEF1,23"). Are there any built-in l ...

Javascript : What is the method to access the array index of a string?

Hey there, I'm struggling with changing a string to invoke an array in JavaScript. Can someone please help me out? So, I have this array: var fruit=['Apple','Banana','Orange']; And I also have a data string from MySQL: ...

Issues with loading an external CSS file in an HTML document

I've been attempting to implement a loading animation using jQuery, but I'm encountering issues with loading the CSS file. I have tried various paths for the css file such as: <link href="css/animation.css" type="text/css" rel="stylesheet"> ...

Utilizing JSON for Google Charts

Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format no ...

Updating the data-target attribute in Bootstrap using CSS (preferably) or JavaScript (as a secondary option)

<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Tips for making a reusable function that utilizes alternating if statements

After hours of experimenting, I finally achieved a smooth scrolling effect with a bounce at the top and bottom. Now, my challenge lies in creating reusable and clean code for this implementation. Perhaps implementing an algorithm could solve this issue? T ...

Exploring the depths of Angular 2: a journey through the

As I delve into Angular 2 internal components and behaviors, a question arises regarding the management of the component tree. In a web application structured with components, the hierarchy forms a component tree where one component is nested within anoth ...

Is there a way to retrieve the quantity of children from an element using protractor?

I am currently working with Protractor and I need to determine the amount of child components associated with a specific element. The element in question belongs to a table category. let table = element(by.css('#myTable')); My objective now is ...

Transferring text to a different textarea in jQuery without the accompanying tags

Can someone help me figure out how to copy the value from one textarea to another without including the HTML tags? Below is the code I have been working with: $(document).ready(function() { $("#go").click(function() { var content = $("#inputdata"). ...

Display loader while waiting for file to be loaded

I am utilizing ajax to retrieve a file. The loading animation is functioning properly with the ajax request, however, the file size is notably large. I am interested in implementing a preloader that will display until the file has finished loading. ...

Error: Parameter missing in express route when using node.js

I am facing an issue with separating parts of my routes into different files Currently, I have a route for /houses/ and another one for /houses/:houseid/bookings The route for /houses/ is stored in a file called routesHouses.js, and I am trying to move p ...

Unpacking a JSON string into a custom object in C# without a predefined structure

Dealing with a JSON response from an API can be tricky when you only need certain data items. Is there a way to efficiently deserialize it into a C# object without the hassle of defining a class for every single element in the JSON result? Or do I have no ...

The route handler for app.get('/') in Express is not returning the input data as expected

I have multiple routes set up, and they are all functioning properly except for the app.get('/') route. When I navigate to 'localhost:3000/', nothing is being displayed in the backend console or on the frontend. The Home component is su ...

WebStorm highlights user-defined Jasmine matchers as mistakes and displays `TypeScript error TS2339: Property 'matcher' does not exist on type 'ArrayLikeMatchers '`

I am currently working on testing a hybrid Angular and Angular.js app using Karma / Jasmine. The previous code utilized custom matchers which worked flawlessly, and these same matchers are being used in the new TypeScript code. Strangely, although the Type ...

What is the best way to verify async actions that update the UI in my React Native application?

Currently, my setup involves utilizing jest alongside @testing-library/react-native. Below is a snippet of code: Upon clicking a button, a function is dispatched: onPress(_, dispatch) { dispatch(getUserAddresses()); }, This dispatched functi ...

Dynamically determine the data type of a value by analyzing the key property within a function

I have created a custom hook that extends the functionality of the useStata function by accepting key and value props; import { Dispatch, SetStateAction, useCallback, useState } from 'react'; export type HandleModelChangeFn<T> = (key: keyo ...

Error validating array with Axios and MongoDB

My Schema includes a tags field for articles. tags: { type: [String], required: [true, "An article must have tags"], enum: { values: [ "science", "technology", "gaming", ], message: ...

Sending a global variable to another controller file in Node.js

I am facing an issue with a global variable called userEmail. The variable is supposed to hold the current user's email value, which is assigned during a post request handling authorization. However, when I try to export this global variable to anothe ...