Explore the values within the Json Array

Attempting to correlate two sets of array values. One set is sourced from a local JSON file, while the other set comes from a backend service.

Data from Local JSON:

var localJsonArray = {
    "records": {
        "cat1": [{
            "id": 1234,
                "label": "a"
        }, {
            "id": 2345,
                "label": "b"

        }],
            "cat2": {

            "id": 12345,
                "label": "c"
        }
    }
}

Data from Backend Array:

The data retrieved from the backend is stored as follows:

var backendArray =[0: "1234", 1: "3456", 2:"4567"];

JS Logic:

$.each( localJsonArray, function( key, value ) {
                var index = $.inArray( value, backendArray );
                if( index != -1 ) {
                    console.log( index );
                }
            });

How can I map the id of the local JSON to the id of the backend JSON? If a match is found, the loop should break; otherwise, it should continue searching for a matching value.

Answer №1

It is not possible to create an array like

var backendArray =[0: "1234", 1: "3456", 2:"4567"];

Instead, you can use the following code:

var localJsonArray = {
    "records": {
        "cat1": [{
            "id": 1234,
                "label": "a"
        }, {
            "id": 2345,
                "label": "b"

        }],
            "cat2": {

            "id": 12345,
                "label": "c"
        }
    }
};
var backendArray =["1234", "3456", "4567"];

$.each( localJsonArray['records'], function( a,b,c ) {
    if(!(b.length == undefined)){
        for(var i = 0;i < b.length; i++)
        {
            var index = $.inArray( b[i].id.toString(), backendArray );
            if( index != -1 ) {
                console.log( index );
            }
        }
    }
    else{
        var index = $.inArray( b.id.toString(), backendArray );
        if( index != -1 ) {
            console.log( index );
        }
    }
});

I hope this explanation has been helpful! :)

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

The registration form's captcha did not prevent the submission of incorrect captchas

This is a PHP register.php page <?php require_once 'config.php'; ?> <?php if(!empty($_POST)){ try { $user_obj = new Cl_User(); $data = $user_obj->registration( $_POST ); if($data)$succ ...

Issue with PHP Ajax Image Upload

I am currently working on setting up an Ajax image upload feature. Unfortunately, I am encountering issues and unable to identify the root cause. <script> $(document).ready(function() { $("#uploadBTN").click(function(event) { ...

Storing JSON data retrieved from an API into a class property using the fetch function: a step-by-step guide

I am faced with the challenge of communicating with a localhost API that I have created in my React application class. This API is responsible for returning a list of JSON data, and my goal is to store this data in a property. Having limited knowledge abo ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

Deciphering JSON data using Swift3

Having trouble parsing JSON with the code snippet below let result = "{ status = ok; token = XXXXX; }" do { let json = try JSONSerialization.jsonObject(with: (result as? Data)! , options: JSONSerialization.Read ...

The impact of returning 0, 1, or -1 on the outcome of array_udiff_assoc() is crucial in determining the end results

I have a good grasp of what it is and what it does, but I'm struggling to understand how it actually functions, especially with the spaceship operator "<=>". Currently, I am in the process of developing some features for spatie/laravel-activity ...

Using an external variable within an internal function in TypeScript

I am facing a situation where I have a variable outside of a function that needs to be updated, but I am unable to access it using "this" as it is not reachable at that point in the code. export class GamesDetailPage { details : any = {}; type : St ...

When attempting to process a JSON string with JQuery's parseJSON() method, no response or error is returned

I've spent some time searching on various forums to find a solution to my problem, but it seems that no one else has encountered it. I am retrieving a JSON string from a field in my MySQL table, which is in the following format: {"width":"10", "heig ...

Verify whether a div element is styled in a specific manner

Upon initial load of my website, if the page is maximized or in fullscreen mode, the comBrand div will have specific CSS properties applied. However, during a resize event, I use the .css() function to adjust the properties of this element so it doesn&apos ...

Linking promises to eliminate nesting

Hi everyone, I am currently working on chaining promises in my code. The initial HTTPS call returns an array of URLs successfully. After that, I loop through them to obtain a JSON object for each one. I am wondering if there is a way to reduce nesting in ...

Is there a way to properly dissect or iterate through this?

I have exhausted all possible methods to retrieve the data, but I am unable to solve this puzzle. The information is organized in a format like the following: [{"code":1000,"day":"Sunny","night":"Clear","icon":113,"languages": [{"lang_name":"Arabic","lan ...

Expand the fields in a JSON file using JQ

Looking to populate a JSON file that currently has no data with the values below using JQ. Attempted code: echo '{"Name": "FileName", "Size": "FileSize", "Action": "Action taken"}' | jq file.json Encountered an issue: Jq: error: clear/0 is ...

Incorporate an onclick function into the text tag element

When working with HTML, I often use text tags like this: <text id="aaa" > text</text> I'm curious if it's possible to add an onclick event to this? I attempted the following: var a = document.getElementById('aaa'); a.el ...

Issues with Three.js materials not rendering properly when loading .obj and .mtl files

I recently downloaded a free 3D model and I'm attempting to view it using three.js. Although the model is loading correctly, there seems to be an issue with the materials not loading properly. Strangely enough, only the wine bottles behind the bar are ...

Button is nested within a closing div causing it to trigger independently without affecting the parent

I have implemented a slideup and slidedown system with some fading effects, but I am encountering an issue with the slide up function. It doesn't seem to reset the display property back to none. For reference, here is a Fiddle link: Slide Up/Down Fid ...

Placing a div on top of a link renders the link unusable

I am facing a situation and require assistance (related to HTML/CSS/JS) I currently have a div containing an image (occupying the entire div space) such that when hovered over, another div with an image is displayed on top (the second div is semi-transpar ...

Preventing data loss in an Ionic array - encountering issues with using this.array.push

When attempting to use the storage get method to fill the array storedArr = [], I encounter the error message .push is not a function: storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : []; The c ...

JQuery click event does not play nicely with Javascript array splice functionality

When using for loops, I noticed that array.splice doesn't seem to be working as expected. The array remains unchanged. I tried moving things around and found that it still doesn't work in Chrome. var menu =['#men','#wmen',&a ...

Unable to display the content

Why isn't the text expanding when I click "see more"? Thanks XHTML: <div id="wrap"> <h1>Show/Hide Content</h1> <p> This code snippet demonstrates how to create a show/hide container with links, div eleme ...

Leveraging _.some in lodash

I'm working on a Typescript code where I need to check if any items in one array are present in another array. Although I am new to lodash, I thought of using _.some for this task. However, the code is currently returning false when I expected it to r ...