Tips for displaying an array of data that corresponds with another array in JSON format

This is the JSON format of the API I am using:

{
    "details":[
        {
            "id": "001",
            "name": "john",
            "age": "19"
        },
        {
            "id": "002",
            "name": "Adam",
            "age": "18"
        },
        {
            "id": "003",
            "name": "Smith",
            "age": "19"
        }
    ],
    "students":[
        {
            "id": "001",
            "status": "Active"
        },
        {
            "id": "003",
            "status": "Active"
        }
    ]
}

What my goal is to compare the id from the details array with the id from the students array and print any matches found.

My Code:

var data, len, len1, id, name, age, status;

const api_url = "API URL";

async function get_data_from_api() {
    
const response = await fetch(api_url);

data = await response.json();

    len = Object.keys(data["details"]).length;
    len1 = Object.keys(data["students"]).length;

    for(let i=0; i< len; i++){
        for(let j=0; j<len1; j++){
            if(data['details'][i]['id'] == data['students'][j]['id']) { 

                id     = data['details'][j]['id'];
                name   = data['details'][i]['name'];
                age    = data['details'][i]['age'];
                status = data['details'][j]['status'];

                document.getElementById('details').innerHTML += "<tr><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td><td>"+status+"</td></tr>";
            }
        }
    }
}

setInterval(get_data_from_api, 1000);

get_data_from_api();

This for loop in my code keeps printing the results repeatedly until the length of the array is reached.

Expected Output:

001 John 19 Active

003 Smith 19 Active

Current Output:

001 John 19 Active

003 Smith 19 Active

001 John 19 Active

003 Smith 19 Active

001 John 19 Active

003 Smith 19 Active

Answer №1

Here is a code snippet that compares and merges two arrays while extracting field names.

let details = [
    {
        "id": "001",
        "name": "john",
        "age": "19"
    },
    {
        "id": "002",
        "name": "Adam",
        "age": "18"
    },
    {
        "id": "003",
        "name": "Smith",
        "age": "19"
    }
];
let students = [
    {
        "id": "001",
        "status": "Active"
    },
    {
        "id": "003",
        "status": "Active"
    }
]


let res = [];
details.map(obj => {
    res.push({ ...obj, ...(students.find((item) => item.id === obj.id)) })
});

console.log(res)

Desired Output:

res = 
[ { id: '001', name: 'john', age: '19', status: 'Active' },
  { id: '002', name: 'Adam', age: '18' },
  { id: '003', name: 'Smith', age: '19', status: 'Active' } ]

Answer №2

To efficiently compare data and track frequencies, consider using an object or map

const dataSet = {
  details: [
    {
      id: "001",
      name: "Eve",
      age: "20",
    },
    {
      id: "002",
      name: "Sarah",
      age: "22",
    },
    {
      id: "003",
      name: "Chris",
      age: "21",
    },
  ],
  users: [
    {
      id: "001",
      status: "Active",
    },
    {
      id: "003",
      status: "Active",
    },
  ],
};

const counts = {};
const matches = [];
// Initialize the count at 1 for each detail O(n)
dataSet.details.forEach((item) => {
  counts[item.id] = 1;
});

dataSet.users.forEach((user) => {
  if (counts[user.id] === 1) {
    matches.push(user);
  }
});

console.log(matches); // [ { id: '001', status: 'Active' }, { id: '003', status: 'Active' } ]

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

If the element does not already exist, use jQuery to append it; otherwise, replace the existing element

Check out this snippet of code: const $element = $("#something").find(".test"); if (!$element.length) { $("#something").append('<div class="test">somecontent</div>'); } else { $element.replaceWith('<div class="test"&g ...

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

What causes the error of inputRef.current being null in CurrencyTextField?

When attempting to target the second 'CurrentTextField' after changing the value of the first 'CurrentTextField', an error occurs stating 'inputRef.current is null'. import React, {useRef } from 'react'; import Curr ...

A guide on breaking down complex mathematical expressions with arrays using javascript

I am looking to store various mathematical expressions that involve basic operations such as addition, subtraction, multiplication, division, exponents, square roots, grouping, etc., along with unique placeholders in the form of a string. const json = { ...

Provide the URL to CasperJS using the Command Line Interface

Currently, I am leveraging CasperJS to assess a webpage. My goal is to enable the passing of a URL as an argument, have CasperJS download and analyze the webpage, and then display the webpage on standard output for use in a BaSH script. Below is the snippe ...

The class javax.swing.JFrame contains several JSON state fields declared within it

I am currently working on developing a 2D tile game and encountered an issue while trying to import items from a JSON file using the GSON library. Each time I run the code, I receive the following error message: java.lang.IllegalArgumentException: class ...

Interactive Event Coordinator

Can a JavaScript script be executed in a specific way until a pop-up element is visible, without relying on setTimeout()? Here are the steps for when the pop-up appears: A user is browsing abc.com and clicks on a button. The pop-up element then shows up ...

Tips for maximizing page layout efficiency without compromising on element visibility

What is occurring https://i.stack.imgur.com/Agjw6.gif The use of .hide() and .fadeIn(200) is resulting in a jittery effect that I would like to avoid. Desired Outcome When the user hovers over the menu icon, the menu icon should vanish the text "Pr ...

Why is $httpBackend failing to populate parameters?

In my application, I utilize a custom $resource service to manage CRUD operations for entities over HTTP. The service is simply wrapped in a custom service without additional functionality: app.factory('coursesService', ['$resource', c ...

Using an Angular 1 controller scope method as a callback for a captcha library

I have a customer in China who needs a specific captcha that functions there. You can find the captcha I need to use at this link: Essentially, there are 4 steps to make it work: Add this line to the label of your html: <script src="https://ssl.ca ...

Updating state using props from Relay QueryRenderer

My React component includes a form for updating database records using the React-Relay QueryRenderer component like this: class Update extends Component { //constructor.. //some stuff render() { return( <QueryRenderer environ ...

Merge two arrays based on date and sort them using Angular.js/JavaScript

I am facing a challenge where I have two JSON arrays, each containing a field named date. My goal is to compare the two arrays and merge them into a single array. Check out the code snippet below: var firstArr=[{'name':'Ram','date ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

Using the section :export in the SCSS :root declaration

In the file test.module.scss, I store all my variables for colors, typography, and more. I want to be able to use these variables in my react components. However, the file starts with :root to define the variables: :root{ --color-white: #fff; --color-b ...

What is the most effective way to delete a single value from a key with multiple values stored in local storage?

This question has come up before, but the solutions provided didn't work for me, which is why I am asking it again. Currently, I am storing values in an array that is then stored in local storage. Here is the object: data.items - 0: {id: 190217270, ...

Hold off on loading the slick slider until we receive a response from the API call

My slick slider was working fine, but I encountered an issue where the slider would apply before receiving a response from an API request. This is my first function: fetchProducts () { this.getProducts ().then(response => { ...

PHP's `json_encode` is failing to properly convert an array and is outputting `{

My system is running CentOS 7.4 with PHP 5.4 installed. $s='a:91:{s:13:"spotsviewvars";s:7:"1916.74";s:13:"100000T18vars";N;s:17:"100000T18S106vars";s:7:"1746.95";s:17:"100000T18S107vars";s:4:"4.49";s:17:"100000T18S108vars";s:4:"8.29";s:17:"100000T18 ...

Ways to automatically scroll through an associated HTML table

Managing two related tables that display the same information in different languages can be a tricky task. In my case, when I use the Key down or Key up functions, only one table scrolls while the other remains stationary. How can I synchronize their scrol ...

Is it possible to refresh the button in an Android app when the object's value

I am facing an issue with updating button values based on an array that stores objects of type Cup. The button should display the value of numberOfPebbles in the cup, and clicking it is supposed to increase all values by 1. I have confirmed this function ...

Retrieving data from a database in PHP and assigning it as the value for an HTML select tag

Seeking assistance on a project to develop a stock management system for an herb factory using PHP with a MySQL database. Currently working on a page that allows the user to edit the value of a bench containing herbs. The bench details have been stored in ...