What is the best way to dynamically display or load an array containing only two values?

Hi, I'm new to Java Script and ReactJS, and I'm currently working on a project to enhance my skills. One of the tasks in this project involves rendering polygonal points on a map using the google-maps-react library.

However, I encountered an issue with the format of the coordinates required by the library for plotting polygons. The data format that I have is different from what is expected by the library:

[
  [
    [-47.7027099655629, -22.26485424139211],
    [-47.70271526762656, -22.26487408404245],
    [-47.70272860122938, -22.26486817968162],
    [-47.70275769033151, -22.26485486960603],
    [-47.7027803963492, -22.26483968832534],
    [-47.7027099655629, -22.26485424139211]
  ]
], [
  [
    [-47.70336262481528, -22.26561084941619],
    [-47.70336542334331, -22.26561213882109],
    [-47.70336596593334, -22.26561211173161],
    [-47.7033695288571, -22.2656092720629],
    [-47.70337969579747, -22.26560034650085],
    [-47.70336262481528, -22.26561084941619]
  ]
]

I'm looking for a JavaScript function or method that can help me transform my coordinate array into the correct format expected by the google-maps-react library. The desired output should look like this:

const coords = {
  coords: [
    [
      { lat: -47.7027099655629, lng: -22.26485424139211 },
      { lat: -47.70271526762656, lng: -22.26487408404245 },
      { lat: -47.70275769033151, lng: -22.26485486960603 },
      { lat: -47.7027803963492, lng: -22.26483968832534 },
      { lat: -47.7027099655629, lng: -22.26485424139211 },
    ],
    [
      { lat: -47.70336262481528, lng: -22.26561084941619 },
      { lat: -47.70336542334331, lng: -22.26561213882109 },
      { lat: -47.70336596593334, lng: -22.26561211173161 },
      { lat: -47.70337969579747, lng: -22.26560034650085 },
      { lat: -47.70336262481528, lng: -22.26561084941619 },
    ],
  ],
};

With almost eight thousand lines of data, manually converting each coordinate is not feasible. So, I am seeking a solution to automate this process.

You can find the original data file I am attempting to use here:

Thank you for your help!

Answer №1

To process an array of arrays, you can utilize the reduce function in conjunction with the map function to generate the desired result.

let arr = [  [    [      [-47.7027099655629, -22.26485424139211],      [-47.70271526762656, -22.26487408404245],      [-47.70272860122938, -22.26486817968162],      [-47.70275769033151, -22.26485486960603],      [-47.7027803963492, -22.26483968832534],      [-47.7027099655629, -22.26485424139211]    ]  ], [    [      [-47.70336262481528, -22.26561084941619],      [-47.70336542334331, -22.26561213882109],      [-47.70336596593334, -22.26561211173161],      [-47.7033695288571, -22.2656092720629],      [-47.70337969579747, -22.26560034650085],      [-47.70336262481528, -22.26561084941619]    ]  ]];
let coords = {
  coords: arr.reduce((a, [c]) => a.concat([c.map(([lat, lng]) => ({lat, lng}))]), [])
};

console.log(coords);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To properly organize and manipulate the data, you will need to use a loop function. Since you are working with multiple arrays, it would be best to utilize a reduce function.

If you are unfamiliar with how a reduce function works, I recommend checking out this resource first: https://www.w3schools.com/jsref/jsref_reduce.asp

Essentially, the process involves iterating through each element and modifying the values as needed. Below is a simple example, which can be adjusted according to your specific requirements:

const newCoordinates = coordinates.reduce((acc, curr) => {
  const newCoordiantes = curr[0].map((coord) => ({
    lat: coord[0],
    lng: coord[1]
  }));
  acc.push([newCoordiantes]);
  return acc;
}, []);

For a demonstration of how this works, you can refer to this live example: https://codesandbox.io/s/sharp-cloud-nfx4k?file=/src/index.js

Answer №3

To modify the format of your array with nested arrays and convert [lat, lng] to { lat, lng }, as well as flatten out a single sub-element layer, you can utilize the map method in JavaScript. This involves cascading two map calls, one of which implicitly destructures the single-element array. Here's an example implementation:

const convert = arr => arr.map(([group]) => group.map(([lat, lng]) => ({ lat, lng })))

const inputData = [[[[-47.7027099655629,-22.26485424139211],[-47.70271526762656,-22.26487408404245],[-47.70272860122938,-22.26486817968162],[-47.70275769033151,-22.26485486960603],[-47.7027803963492,-22.26483968832534],[-47.7027099655629,-22.26485424139211]]],[[[-47.70336262481528,-22.26561084941619],[-47.70336542334331,-22.26561213882109],[-47.70336596593334,-22.26561211173161],[-47.7033695288571,-22.2656092720629],...console-wrapper { max-height: 100% !important; top: 0; }

Please note that the structure of your input data may require adjustment, as it appears to be missing an outer array encompassing the multiple arrays shown. I have included this correction in my example for the code to function correctly.

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

Creating a Standard DIV Element (JavaScript Code)

Just a quick question here. http://jsfiddle.net/fkling/TpF24/ In this given example, I am looking to have < div>Bar 1</div> open as default... Any suggestions on achieving that? That would be all for now. Thank you so much! :D The JS script ...

Express Session doesn't remove the variable assigned

While developing a web application using Node Express, I encountered a simple issue in my new project. Despite setting a session variable to null, the old session data is still being called. Seeking assistance to resolve this issue. I utilized express-ses ...

Pinpointing a specific region within an image by utilizing offsets

Would it be possible to detect a specific area within an image using a predefined set of image offsets? Here is the image and accompanying offsets: Sample Image Below are the sample image offsets for the highlighted area: Offset(63.4, 195.2) Offset(97.7 ...

How can I omit a child element from a list of children using jQuery?

Within my website's structure, I have a parent div element with the ID #mmm-a that is initially set to be hidden using the CSS property visibility: hidden as a result of a previous onclick function. To make this parent div reappear when clicked, I am ...

reconfigure form credentials with JavaScript

I am currently working on a form that includes a textbox and a button for submitting data using ajax. <input type="password" id="password" /> <button id="addaccount" onclick="showload();">Add</button> When the user clicks on the button, ...

Negative vibes with for/in loop

My script is short and simple: hideElements = arguments.shift().split(','); for (iterator in hideElements) { console.log('--> hiding ' + hideElements[iterator]); lg_transitions({kind:"slide-up"}, {target: hideElements[iterat ...

The node.js express framework is unable to fetch the URL and data from the node server

Attempting to create a basic application to retrieve data from a nodejs server. But encountering issues with accessing the file in both the browser and POSTMAN. Despite multiple attempts to verify the URLs, I have been unsuccessful. Below are the files i ...

What is the best way to achieve varying margins when adding divs in CSS?

Encountering CSS margin issues when adding new divs. Desiring a large margin between the Create Div button and minimal margin between Example Text Here. The desired outcome Margin is too small between Create Div button and Example Text Here, but good bet ...

What could be preventing the toggle from functioning properly with the other DIVs?

Check out this fiddle link! The issue is that only the first top div is functioning properly. [http://jsfiddle.net/5Ux8L/4/][1] Here is the HTML code: <div id="top">top </div> <div id="box">box </div> <div id="top">to ...

What distinguishes passing an event handler directly versus encapsulating it within an arrow function in React?

Are there any distinctions in how these 2 inputs utilize the event handler in terms of functionality or performance? export default function App() { const handleChange = e => { console.log(e.target.value); } return ( <div className=& ...

When iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...

Enhance the functionality of the Bootstrap navbar by enabling the slideUp and slideDown effects

I can't get jQuery's slideUp and slideDown methods to smoothly animate the Bootstrap navbar. When I tried using the slideUp method, the navbar only slid up a little before disappearing completely, and the same issue occurred with the slideDown me ...

`Is it necessary to handle textStatus when encountering an HTTP error during an AJAX request?`

When utilizing jQuery and encountering an AJAX request failure attributed to an HTTP error (e.g., 500 Internal Server Error), what exactly is the assigned value of the textStatus parameter within the error handler function? For instance, $.ajax(...).fail( ...

jQuery does not function properly when used with string variables

Why am I experiencing different results in Google Chrome when using a hard-coded string versus storing the same string in a variable? While the hard-coded string works properly, the same string stored in a variable does not produce the expected outcome. ...

Establish a pathway based on an item on the list

I need to create a functionality where I can click on a fruit in a list to open a new route displaying the description of that fruit. Can someone guide me on how to set up the route to the 'productDescription.ejs' file? app.js: const express = ...

Exploring the variable scope in Node.js with a focus on separating routes

My routing configurations are stored in an external folder. Find them in the ./routes directory This is how I set up my routes within the server.js file: app.get('/', routes.index); app.post('/validation', register.valid); The reg ...

Managing and retrieving data in bulk from an indexed database as JSON format

I am currently developing an application that utilizes IndexexDB for local data storage. I am looking for a way to extract and insert large amounts of data from an indexed DB in JSON format. Below is the code snippet illustrating what I have accomplished s ...

At times, the map may only be visible in the top left corner of its designated container

Currently, I am integrating the Google Maps API v3 for JavaScript into my project. However, I am facing an issue where the map only appears in the upper left corner under certain circumstances. To visualize this problem, you can visit this link and click ...

Iteratively modify each essential attribute of a JSON object

In my data set, I have moisture levels recorded at various timestamps in a JSON object: { "values": { "21-Aug-2020 20:28:06:611591": "58.59", "21-Aug-2020 20:28:09:615714": "71.42", "21-A ...

Ways to eliminate class from HTML code

Trying to detect if a navigational element has a specific class upon click. If it has the class, remove it; if not, add it. The goal is to display an active state on the dropdown button while the dropdown is open. The active state should be removed when a ...