Changing JSONArray's to JSON Object in JavaScript

I have a task at hand where I need to combine two JSON arrays into a single JSON object that I have retrieved from an ajax call. Here is the code snippet that shows how I am fetching and storing the data:

        var a = []; 
        var b = [];

        var docsDatafromSOLR = response.response.docs;
        var lengthOfSOLR_response = docsDatafromSOLR.length;

        for (var i=0; i< lengthOfSOLR_response; i++) {
            a.push({
                latitude: docsDatafromSOLR[i].latitude,
                longitude: docsDatafromSOLR[i].longitude
            });

        }

After this operation, array 'a' would look something like below:

       "a": [
        {
         "latitude": 23,
         "longitude":43
        },
         {
         "latitude":42,
         "longitude":67
         } 
      ]

'Array b' will follow a similar structure as well.

My question now is, how can I transform the individual JSON arrays 'a' and 'b' into a format like the one shown below? I have been searching for the syntax with no luck so far.

{
"1": {
    "a": {
        "latitude": "41",
        "longitude": "-73"
    },
    "b": {
        "latitude": "32",
        "longitude": "-29"
    }
},
"2": {
    "a": {
        "latitude": "47",
        "longitude": "-69"
    },
    "b": {
        "latitude": "42",
        "longitude": "-35"
    }
}
}

Answer №1

An effective approach that comes to mind involves utilizing Array.prototype.map method.

By simply mapping one array to the desired outcome, for example:

var output = a.map(function(element, idx) { 
    return {x: element, y: b[idx]}
});

Answer №2

give this a shot:

var array1 = {
    "red": [
        {
            "x-coordinate": 0,
            "y-coordinate":0
        },
        {
            "x-coordinate":5,
            "y-coordinate":5
        } 
    ]
}

var array2 = {
    "blue": [
        {
            "x-coordinate": 10,
            "y-coordinate":10
        },
        {
            "x-coordinate":20,
            "y-coordinate":20
        } 
    ]
}


var result = {}; 
var key1 = Object.keys(array1)[0];
var key2 = Object.keys(array2)[0]; 

for(var i=0; i<array1[key1].length; i++){  
    result[i] = {};
    result[i][key1] = array1[key1][i];
    result[i][key2] = array2[key2][i];
}


console.log(JSON.stringify(result,null,2)); 

result:

{
  "0": {
    "red": {
      "x-coordinate": 0,
      "y-coordinate": 0
    },
    "blue": {
      "x-coordinate": 10,
      "y-coordinate": 10
    }
  },
  "1": {
    "red": {
      "x-coordinate": 5,
      "y-coordinate": 5
    },
    "blue": {
      "x-coordinate": 20,
      "y-coordinate": 20
    }
  }

Answer №3

Trying to determine the exact placement for this piece of information can be a bit tricky, but you could attempt to parse your ajax response data like this:

.done(function (data) {
    JSON.parse(data); //If the response is correctly formatted, the data should now be in object form.
})

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

Incorrect credentials trigger an error in Nodemailer

Currently, I am utilizing nodemailer to handle email submissions from a registration form. Below is the code for my registration form: <form action="/registration" method="post"> <h3 class="text-center" style="font-family: 'champagne-l ...

Tips for verifying that input is provided in a text field when the checkbox is marked

Can someone help me with validating a form where the user must enter data in a text field if they check a checkbox? I have JavaScript code for checkbox validation, but need assistance with text field validation. Thank you! $(document).ready(function () ...

Guide on incorporating vanilla JavaScript into a personalized Vue component

I'm currently working on incorporating a basic date-picker into a custom Vue component. Since I am not utilizing webpack, I want to avoid using pre-made .vue components and instead focus on understanding how to incorporate simple JavaScript into Vue. ...

Utilizing Vanilla JavaScript to retrieve information from a HTML table

I am currently running my website on XAMPP and I have a database connection set up that I can use. In my database, I have three drop-down menus labeled Translations, Books, and Chapters where the data for each is stored. My goal is to utilize Vanilla JS ...

Generating a highchart by retrieving JSON data using AJAX

I'm currently working on generating a basic chart on a webpage using data from a MySQL database that is fetched via a MySQL script. My main challenge lies in understanding how to combine the ajax call with the necessary data for the chart. I'm n ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Utilizing a Single Background Image Across Several Div Elements

Let me illustrate my question using a sequence of images. The div container is set to display the background image as follows: In addition, there will be tile-shaped divs layered on top of the image: I aim to have the background image visible only withi ...

"Encountered an issue with the validation upon clicking the submit

Here is my sample code snippet <form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submitForm();"> Here is the JavaScript function I am using <script type="text/javascript"> function submitForm() { var ...

Upon invoking useEffect, the information is displayed, only to encounter an error when attempting to access

After fetching data from a 3rd party API and logging it in the console, I encounter the error message Uncaught TypeError: Cannot read properties of undefined (reading 'tweet_results'). Despite having conditions in place, the data does not display ...

Discovering the closest date among the elements in an array

Currently, I am facing an issue while trying to identify the highest date within an array of objects which have varying dates assigned to each one. The code seems to be functioning well when the dates are above January 1st, 1970, however, any date prior to ...

Transform the JavaScript onclick function into jQuery

I have been working on incorporating my javascript function into jQuery. The functionality I am aiming for is that when you click on a text (legend_tag), it should get added to the textarea (cartlist). <textarea id="cartlist"></textarea& ...

Sliding content with the grace of a visual journey

I'm currently working on a content slider that is very similar to this one. My goal is to make it rotate automatically, but I've been struggling to get it to work. I've attempted various methods, including triggering a click event on the lin ...

Issue with .html causing .hover to malfunction

Attempting a basic image rollover using jQuery, I've encountered an issue with the code below: HTML: <div class="secondcircle" id="circleone"> <p> <img src="/../ex/img/group1.png"> </p> </div> JS: $("# ...

Using AngularJS to Send Elements to Scripts and Selectors

When I use the following template: <div id="container"> <textarea name="message"></textarea> <button value="send" ng-click="testMethod($parent)"> </div> In the JavaScript code: $scope.testMethod = function(element) ...

JavaScript doesn't pause for the data to come back, resulting in an undefined value

When I call the function "classTableData" on a button click, my allData variable becomes undefined. The problem seems to be that it processes the next line of code without waiting for the results, causing allData to remain empty. Can anyone provide some ...

Convert a string into characters on a two-dimensional array in Java

I need to populate a 2D char array with 5 words. Each word must be broken down into individual characters and placed in one row of the array. String str = "hello"; char[][] wordsArray = new char[10][5]; wordsArray[0] = str.toCharArray(); I am encounterin ...

What is the best way to change the "MuiPaper-elevation1" attribute in a Card element within Material-UI?

My Card component in HTML looks like this: <div class="MuiPaper-root MuiCard-root makeStyles-Card-5 MuiPaper-elevation1 MuiPaper-rounded"> I want to change MuiPaper-elevation1 to MuiPaper-elevation0 to remove the shadow. I attempted: ...

Cordova iOS displaying problem when loading Google Maps

Whenever I launch Google Maps through a google map URL for the first time (if Google Maps is not already running in the background), directions do not display. However, if Google Maps is running in the background, the directions show up as expected. I am ...

What could be the reason the server actions in nextjs 13 are not functioning correctly?

I am currently working on a project to retrieve data from mockapi.io, a mock API. However, I am encountering an issue where the fetched data is not displaying in the browser. There are no visible errors, and the browser window remains blank. Interestingly, ...

Obtaining the difference in values of a PHP array

I'm having trouble understanding the difference between the following. Can someone explain it to me in a simpler way? Even after reading about PHP arrays, I still can't figure it out. print $myArray[0]->token and print $myArray[0]["token"] ...