Exploring nested JSON objects with Alasql

I am currently working with a JSON object that represents two companies, Ebay and Amazon.

For the Ebay Object:

{
    __v: 0
    _id: "56e192f0aea7131c15513328"
    headquarters: "New York"
    name: "Ebay"
    productCategories: [{
        _id: "56e193beaea7131c1551332d"
        name: "Footwear"
        products: [{
            name: 'Shiela',
            price: 420,
            totalSales: [10, 20]
        }, {
            name: 'Parry',
            price: 350,
            totalSales: [50, 20]
        }]
        totalSales: 100
    }, {
        1: Object
        _id: "56e193beaea7131c1551332e"
        name: "Clothes"
        products: [{
            name: 'Kurta',
            price: 210,
            totalSales: [60, 80]
        }, {
            name: 'Sun Glass',
            price: 785,
            totalSales: [5, 25]
        }],
        totalSales: 170
    }]
}

And for the Amazon Object:

{
    __v: 0
    _id: "56e192f0aea7131c15513328"
    headquarters: "New York"
    name: "Amazon"
    productCategories: [{
        _id: "56e193beaea7131c1551332d"
        name: "Footwear"
        products: [{
            name: 'Shiela',
            price: 280,
            totalSales: [10, 20]
        }, {
            name: 'Parry',
            price: 785,
            totalSales: [50, 20]
        }]
        totalSales: 100
    }, {
        1: Object
        _id: "56e193beaea7131c1551332e"
        name: "Clothes"
        products: [{
            name: 'Kurta',
            price: 150,
            totalSales: [60, 80]
        }, {
            name: 'Sun Glass',
            price: 485,
            totalSales: [5, 25]
        }],
        totalSales: 170
    }]
}

I aim to compare and extract common product names and prices between both companies based on their shared product categories.

While attempting to do so, I encountered an error when running a specific query. Here is the code snippet:

alasql('SELECT products.name,products.price FROM ? as category1 join ? as category2 using products.name', [$scope.company1.productcategories,$scope.company2.productcategories], function(data) {
                    console.log("Query executed");
                    console.log(data);
                });

I believe there might be a mistake in the query execution method. Any guidance on how to correctly achieve this comparison would be greatly appreciated.

Best Regards, Sabarisri

Answer №1

Initially, working solely with local memory doesn't require an asynchronous operation. Therefore, your first step should involve utilizing the following code:

var result = alasql('SELECT productCategories->0->name FROM ?',[$scope.selectedCompanies]);

You are almost there. Your objective is to query specifically on the productCategories data - thus, you should execute:

var result = alasql('SELECT name FROM ?',[$scope.selectedCompanies.productCategories]);

Extra tip: If you intend to perform a join operation, consider implementing something similar to the following:

var result = alasql('SELECT p.name, d.stock FROM ? p JOIN ? d ON p.name = d.company',[$scope.selectedCompanies.productCategories, $scope.otherData]);

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

Display an image labeled as "not specified" using multer

I'm attempting to upload a picture using multer, here is my server-side code: const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './uploads/') }, filename: function (req, file, cb) { ...

When submitting a form with the jQueryForm plugin, take action on the form by selecting it with `$(this)`

I have a situation where I have multiple forms on one page and am utilizing the jQuery Form plugin to manage them without having to reload the entire page. The issue arises when I need some sort of visual feedback to indicate whether the form submission wa ...

Adding dots between page numbers when using ReactJS/Javascript Pagination can be achieved by implementing a specific method

I have created a pagination component using React JS. Currently, it only displays all the page numbers, but I want it to show dots when there are more than 8 total pages. Here's how I envision it: c. When total is less than 9 pages: Page 1 selecte ...

Fill various dropdowns with a list or array of values discreetly without displaying the populated values on the visible interface

I have an array with values 1,2,3,4. Using an add function, I am able to create multiple dropdowns. By default, the first dropdown always has a value of one when initially set up. When we press add and populate the second dropdown with values 2,3,4, tho ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Encountering a Typescript error while attempting to utilize mongoose functions

An example of a User interface is shown below: import {Document} from "mongoose"; export interface IUser extends Document{ email: string; password: string; strategy: string; userId: string; isValidPassword(password: string): ...

EventBus emitting multiple times until the page is refreshed

Trying to make use of the EventBus in Vue.js to transfer data from one method to another. In my setup, I've got two methods named one() and two(). Here's how I'm implementing the EventBus: one() { EventBus.$emit("this:that", data); } And ...

Creating bespoke form components with AngularJS

I am looking to develop a unique form element that functions in the same way as traditional form elements in terms of validation and value, but with an object as its value. For instance, I want to create a "birthday element" that, when clicked, displays a ...

The click event is activated following the :active selector being triggered

My Angular application features a button with a slight animation - it moves down by a few pixels when clicked on: &:active { margin: 15px 0 0 0; } The button also has a (click)="myFunction()" event listener attached to it. A common issue arises w ...

"Troubleshooting a formatting problem with saving JSON data to a file using PHP

I am currently working on a PHP script that generates a JSON encoded file from user input. $name =$_POST['n']; $age = $_POST['a']; $occ= $_POST['n']; $country = $_POST['n']; $jsoninfo = array('name'=>$ ...

Transforming a JavaScript object into a nicely formatted string

How can I format an object to be displayed as a structured string like with <pre>, without using jQuery? This is how my object currently appears when using console.log. Object title: "Another sting" type: "tree" options: Object pagin ...

Encountering a snag when trying to grant notification permission in the Expo app

I am experiencing an issue with a simple code that previously asked for notification permissions. However, I am now encountering the following error: "Error: Encountered an exception while calling native method: Exception occurred while executing exp ...

Resizing the Canvas in Three.js with GLSL

I'm currently facing challenges with maintaining the proportions when resizing the window to smaller sizes on mobile devices as shown in this CodePen. The lines and interaction become difficult to see on mobile screens. Is there a solution to address ...

Creating a hover effect for displaying image masks

My website features a profile page displaying the user's photo. I am attempting to create a functionality where when the user hovers over their photo, a transparent mask with text appears allowing them to update their profile picture via a modal. How ...

What is the process for accessing the updated store states immediately after triggering an action in a component method?

I rely on Redux for managing state in my React JS application, but I am facing an issue with an event handler related to a button in my class component. Here is the code snippet: handleStartBtn = e => { const name = document.getElementById("n ...

V-model prevents checkbox from being checked upon clicking

codesandbox: https://codesandbox.io/s/github/Tapialj/AimJavaUnit6?file=/src/frontend/src/components/AddMovieForm.vue I am currently working on implementing a feature where I need to collect an array of selected actors using checkboxes. I have set up a v-m ...

The dilemma of selecting objects in Three.js

Currently, I am developing a small web application that utilizes three.js. However, I have encountered an issue: I created a prototype with my three.js content and everything functions correctly (the canvas size in the prototype matches the browser window ...

Encountered an error stating 'Cannot read property 'user' of undefined' while attempting to generate a user document during account creation using Firebase

I'm having trouble adding the user ID to a new collection named 'accounts' during account creation. I keep encountering an error that says 'Cannot read property 'user' of undefined'. Can someone please help me troubleshoo ...

Filtering Django queryset based on "lists" of values for multiple columns

Imagine I have a model structure like this: Class Person(models.Model): firstname = models.CharField() lastname = models.CharField() birthday = models.DateField() # etc... Now, let's say I have two lists: one with first names first_l ...

Challenges faced with the $_POST["var"] variable in Yii Controller

I am facing an issue with $_POST["var"] in my controller. It appears to be empty. How can I capture the string entered in my textField? View <?php Yii::app()->clientScript->registerCoreScript("jquery"); ?> <script type="tex ...