A guide to performing a LEFT JOIN on two JSON data sources from external URLs

I've been attempting to achieve the following outcome using external JSON data but haven't had any luck finding a solution on search engines or forums. Can anyone provide assistance with this? Thank you in advance.

people = 
[{id: 1, name: "Tom", carid: 1},
{id: 2, name: "Bob", carid: 1},
{id: 3, name: "Sir Benjamin Rogan-Josh IV", carid: 2}];

cars=
[{id: 1, name: "Ford Fiesta", color: "blue"},
{id: 2, name: "Ferrari", color: "red"},
{id: 3, name: "Rover 25", color: "Sunset Melting Yellow with hints of yellow"}];

var res = alasql('SELECT people.name AS person_name, cars.name, cars.color \
    FROM ? people LEFT JOIN ? cars ON people.carid = cars.id',[people, cars]);

Result:

[{"person_name":"Tom","name":"Ford Fiesta","color":"blue"},{"person_name":"Bob","name":"Ford Fiesta","color":"blue"},{"person_name":"Sir Benjamin Rogan-Josh IV","name":"Ferrari","color":"red"}]

This is how I'm trying to access external JSON files:

people.json

[{id: 1, name: "Tom", carid: 1},{id: 2, name: "Bob", carid: 1}, {id: 3, name: "Sir Benjamin Rogan-Josh IV", carid: 2}]

cars.json

[{id: 1, name: "Ford Fiesta", color: "blue"},{id: 2, name: "Ferrari", color: "red"},{id: 3, name: "Rover 25", color: "Sunset Melting Yellow with hints of yellow"}]

JS Code

$(document).ready(function() { 
         $.getJSON('http://example.com/people.json', function(data) { 
                    people = JSON.parse(data);
                }); 

         $.getJSON('http://example.com/cars.json', function(data) { 
                    cars = JSON.parse(data);
                }); 


        var res = alasql('SELECT people.name AS person_name, cars.name, cars.color \
        FROM ? people LEFT JOIN ? cars ON people.carid = cars.id',[people, cars]);

        document.getElementById('id01').textContent = JSON.stringify(res);
}):

I'm encountering the following error in the console

Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Object.success (list.html:26)
at c (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at l (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)

Answer №1

To complete your task, simply loop through each individual and match their car details accordingly.

Here is a sample code snippet using the for of loop. You can also utilize the map operator for the same functionality.

people = [{
    id: 1,
    name: "Alice",
    carid: 1
  },
  {
    id: 2,
    name: "John",
    carid: 1
  },
  {
    id: 3,
    name: "Emma Smith",
    carid: 2
  }
];

cars = [{
    id: 1,
    name: "Toyota Camry",
    color: "silver"
  },
  {
    id: 2,
    name: "BMW X5",
    color: "black"
  },
  {
    id: 3,
    name: "Honda Civic",
    color: "white"
  }
];

const result = [];
for (const person of people) {
  const car = cars.filter(entry => entry.id === person.carid)[0];
  result.push({
    person_name: person.name,
    name: car.name,
    color: car.color
  });
}

console.log(result)

Answer №2

I have discovered the solution.

 const getPeopleData = () => {
    var requestpeop = new XMLHttpRequest();
    requestpeop.open('GET', 'people.json', false);  // `false` makes the request synchronous
    requestpeop.send(null);

    if (requestpeop.status === 200) {// That's HTTP for 'ok'
      var people = JSON.parse(requestpeop.responseText);
    }
}

const getCarsData = () => {
    var requestcar = new XMLHttpRequest();
    requestcar.open('GET', 'car.json', false);  // `false` makes the request synchronous
    requestcar.send(null);

    if (requestcar.status === 200) {// That's HTTP for 'ok'
      var cars = JSON.parse(requestcar.responseText);
    }
}

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

Incorporate action icons (such as edit and delete) into a table in React.js using material-ui

Within my existing table, I utilized a library known as react-bootstrap-table-next This library effectively displays data in a table format with values originating from a JSON response Now, my goal is to integrate an Action column that includes options f ...

How to retrieve a property with a colon in JavaScript object

After parsing XML into JSON with xml2js, I found elements with colons like this: obj = { "data:example":"smthing"}; Is there a way to directly access these elements in JSON? Any tips or tricks? Thank you! ...

Synchronize two div elements with JavaScript

The demonstration features two parent divs, each containing a child div! The first parent div's child div is draggable and resizable using JQueryUI. There are events for both dragEnd and resizeEnd associated with this div. The goal is to synchronize ...

Concealing a button within a specific interface

I am currently facing an issue with a data table that includes two control buttons: edit and save. My problem lies in hiding the save button on the initial preview. Basically, what I want to achieve is displaying only the Edit button on the first page. Wh ...

Yii employs the use of quickdlgs to efficiently generate fresh entries within the CGrid view

Within my web application, I am attempting to implement an iframe button using quickdlgs to create new records. However, upon clicking the iframe button, instead of being directed to the 'create' webpage, I am presented with an empty iframe. Here ...

The process of converting JSON arrays to CLOB in Oracle databases

I need to construct a child JSON payload to complement the main payload. My query is about how to convert these arrays into a CLOB in order to pass them as a PSLQL parameter. Below is the code snippet: Declare l_children json_array_t; p_clob CLOB cursor ...

Discontinue playing videos embedded in iframes on Dailymotion

I'm currently working on creating a slider that includes videos from multiple providers, and I need to ensure that the videos stop when changing slides. So far, I've successfully implemented this feature for Vimeo and YouTube without making any a ...

What is the functionality of Mongoose for handling multiple updates?

Array; arr=[ { id: [ '5e6e9b0668fcbc7bce2097ac', '5e6e9b0e68fcbc7bce2097af' ], color: [ 'a', 'b' ] } ] Models; const varyant = Models.varyant function; Promise.all( arr.map((item)=>{ return var ...

Utilizing the require pattern to integrate JavaScript functionality into HTML

Have: project |- consume_script.js |- index.html Need index.html to be like: <html> <head> </head> <body> <script src="consume_script.js"></script> </body> </html> Issue: consume_script ...

Ways to determine if an AngularJS modal is currently displayed

I am currently in the process of determining whether a modal is opened or closed. However, I keep encountering an error that says "cannot read property of open." To address this issue, I realize that I need to connect with $modal.open and retrieve the resu ...

Limiting the number of times a specific character appears using a regular expression

Currently, I am in search of a regular expression that allows me to set a limit on the number of times a special character can appear. For instance, if I want to restrict the occurrence of * to a maximum of 5 times in the entire text, then the output shou ...

There is a random section that keeps crashing on the website

I have encountered a bug on my one-page Bootstrap template website. One of the sections is causing issues after multiple page refreshes. Despite checking the console for errors, I am unable to identify the source of the problem. Here is the HTML code for ...

What is the best way to design a regular expression that will only match up to 12 numbers?

Is there a way to construct a regular expression that will validate a string containing up to 12 digits only? Thank you! ...

Using Angular to send data to a WCF JSON endpoint

I've been trying to send a request to a WCF JSON service endpoint from Angular, but I haven't had any luck so far. The service has been tested through other methods and is functioning properly for the specified URL. When checking with Firebug, I ...

Obtaining JSON data from a PHP script using AngularJS

I've been exploring an AngularJS tutorial on a popular website called w3schools. Check out the tutorial on w3schools After following the tutorial, I modified the script to work with one of my PHP scripts: <!DOCTYPE html> <html > <sty ...

The React app I've been working on has a tendency to unexpectedly crash when reloading the code from time

Dealing with a frustrating issue here. I've been working on an app and for the past few weeks, it keeps crashing unexpectedly. It seems to happen more frequently after saving my code to trigger a reload, but it can also just crash randomly while navig ...

What could be causing render_template to fail when attempting to update the same parameters more than once?

Lately, I've dived into the world of Flask, MongoDB, and ElasticSearch. So far, my MongoDB and ElasticSearch setups are running smoothly. However, I've encountered an issue with generating a list of dictionaries and displaying them on my HTML we ...

The format for the time period should be as follows: day, month, year, hour, and minute - dd,

Hey there! I need some assistance with validating the JSON data that I am sending to the backend. The time period in the JSON should follow this format: dd,MMM,yyyy,hh,mm. Here's a snippet of my JSON: { "equipmentID":"234", "modality":"healt ...

Leverage the power of jQuery's .filter() method to pinpoint and target specific text

HTML: <p class="greeting"> hello, my name is kevin. what's yours? </p> jQuery: $("p.greeting").filter(function (){ return $this.text() === "my name is"; }).css("background", "green"); I am attempting to find and highlight the phra ...

An example of using quotes within quotes is an HTML tag embedded within JavaScript code

Currently, I'm working on a JavaScript code where clicking assigns the function getImage the source of an image to be displayed later on the page. The issue I'm facing revolves around dealing with quotation marks. <img src="bill.jpg" class=" ...