"Learn the process of converting JSON to an array in JavaScript within the context of ASP .NET Core MVC

I've developed an ASP.NET Core MVC 2 application to display markers on a map. The Model and Controller are as follows:

Model:

    public class MarkersModel
{

    public string title { get; set; }

    public double lat { get; set; }

    public double lng { get; set; }

}

Controller:

    public class MarkersController : Controller
{
    public IActionResult Index()
    {
        return View("Markers");
    }

    public IActionResult GetMarkers()
    {
        // Define landmarks, buildings, stops, and others
        var model1 = new MarkersModel {lat = 53.43382, lng = 14.55559, title = "Galaxy"};
        var model2 = new MarkersModel { lat = 53.42800, lng = 14.55124, title = "Kaskada" };
        
        // Add more models here...

        return Json(new {model1, model2 });

    }
}

AJAX is used to retrieve data from the controller and store it in a variable called "response":

function getData() {

$.ajax({
    url: '/Markers/GetMarkers', 
    type: 'POST',
    dataType: "json",
    data: JSON.stringify(),
    contentType: 'application/json; charset=utf-8',

    success: function(response) {
        initMap(response);
    },

    error: function(error) {
        alert('error');
    }

The function initMap displays the JSON object in the console.log(data):

function initMap(data) {

console.log(data);

    var map = new google.maps.Map(
    document.getElementById('map'),
    { zoom: 10, center: { lat: 53.42894, lng: 14.55302 } });

// Parsing JSON data
var myMarkers = $.parseJSON(data);

}

How can I convert JSON to a Javascript array or add markers to the map?

Answer №1

Try out this solution to resolve the issue:

//Parse the JSON array
var parsedJsonArray = JSON.parse(yourJsonArray);

// Create an empty JavaScript array
var jsArray = [];

// Iterate through the JSON array and add each item to the JavaScript array
for (var element in parsedJsonArray){
  if (parsedJsonArray.hasOwnProperty(element)){
    // Add the item to the JavaScript array
    jsArray.push(element);
  }
}

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

"React-pdf throws an error stating that `Buffer` is not defined

I am encountering an issue while trying to utilize the react-pdf library to create pdf files. Upon attempting this, I am facing the following error: BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no ...

Rounding to Significant Digits: The Mystery of Vanishing Zeros

I am currently working on a JavaScript mathematics package that focuses on rounding to different significant figures (S.F.), but I have encountered a problem that is proving challenging to solve. Before delving into the issue, let me provide some backgrou ...

The Datepicker in MUI - React is unable to recognize the `renderInput` prop on a DOM element

I've been experimenting with the MUI version 5 DatePicker component. I followed the example provided in the MUI documentation's codesandbox demo. Here is how my component looks: const MonthPicker: FC = () => { const [value, setValue] = Rea ...

Is there a method to determine the height of the viewport if the DOCTYPE is not specified in Chrome, Firefox, or Safari?

How can we accurately determine the viewport's height even if the DOCTYPE is not specified? When the DOCTYPE is missing, values that would typically be around 410 may instead show as 3016. Is there a solution for finding the viewport's height wi ...

Once a unique email address has been created, I aim to reuse it for future correspondence

Issue: During the application process, I encounter a dilemma when prompted to input an email address and confirm it in a separate text field. To automate this task, I rely on webdriverJS for coding. My approach involves generating a random email address u ...

The webpage appears to be experiencing issues with the append() function

I'm having trouble appending a form and it's not working properly. Can anyone help me with a solution? Whenever I click the button below: <div class="col-md-4"> <span href="" class="btn btn-info btn-lg dashboard-icon append">Assig ...

What issue is being encountered with this JavaScript generated by PHP?

PHP on the host generates JavaScript code that results in an error stating: missing ; before statement The generated JavaScript code looks like this: try{ obj = document.getElementById('subcat'); }catch(e){} try{ obj.innerHTML = ...

Why is Firefox failing to emit after establishing a connection on the client side?

When it comes to my game, everything seems to work smoothly with other browsers except for Firefox. The issue is quite small but major in nature - why does Firefox fail to emit the "new-player" message after socket connection? In contrast, all other browse ...

What is the best way to extract keywords from a search engine using ASP.NET?

Can anyone provide guidance on how to optimize the keywords entered in a search engine to navigate to my website using ASP.NET webforms? Your assistance is greatly appreciated. Thank you. ...

Guide on Verifying File Existence through URL using JavaScript

Can someone assist me with this code? http://jsfiddle.net/geetyn6f/422/ I am looking to input the URL in the designated field. Upon clicking 'Check', I want the result to display in the second input instead of an alert. URL: <input type="t ...

JavaScript - What is the best way to remove an existing value from a DIV element?

I'm currently developing a game where two players engage in combat. Currently, I have managed to set up the system so that the player's health points (hp) are displayed as 100. However, when an event occurs causing the player to take 10 damage, ...

A guide to incorporating scroll-triggered animations into Next.js 13

Trying to figure out the best way to incorporate scroll-triggered animations in Next.Js 13. I attempted to utilize a library like AOS, but it requires initialization within a useEffect hook for client-side rendering. If I want AOS functionality available ...

Obscure issue encountered during production: `Type Error: e is not defined`

After putting my Vue app into production, I encountered a perplexing issue with a specific component that throws an error message I can't track down. The problem seems to be related to the bundling process since it only occurs in production mode. Ste ...

Utilizing a PHP Class object in Javascript by accessing its properties within a Javascript function

I'm struggling to access the attributes of an object within a JavaScript function that I created. This object was originally a PHP object that I converted to JSON using json_encode() In my project, there is 1 PHP file and 1 external JS file. In the ...

Attempting to reset my react-final-form fields led to receiving an empty object as the values instead

Currently, I am facing a situation where I need to clear all field values except for "retainThisObj" upon the initial page load. The problem I encountered is that my { } ended up empty, meaning that my "retainThisObj" was also deleted. ...

Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line: stars[i].x = Math.floor(Math.random() * w) Even though stars is defined in the code, the issue persisted. $(document).ready(f ...

What could be causing the CSS to malfunction when the dropdownlist is updated without refreshing the page?

Currently, I have implemented DropKick CSS/JQuery to customize the appearance of my asp:DropDownList: <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <asp:DropDownList AutoPostBack=" ...

Tips for ensuring only one dropdown is opened at a time

Hey there! I've been struggling with getting my dropdowns to open one at a time on my website. I attempted to hide them all by default, but they still insist on opening simultaneously. Any ideas on what I might be overlooking? Thank you for your help! ...

How to utilize regular expressions in JavaScript without the need to instantiate a regex object

Here is a code snippet that checks a URL for a specific pattern: var url = "https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regex%20javascript"; var patt = new RegExp('https?:\/\/[^/]+\.google ...

Monitor the status updates by utilizing APEX.SERVER.PROCESS functionality

Environment: Oracle APEX v5.1.2 with Oracle 12c R2 Database I have created a report based on the columns of a table named MY_TASK. The columns include: TASK_ID (Primary Key), TASK, TASK_STATUS (from TASK_CHECKER.task_status) In addition, I use another t ...