Transformation of Arrays to Modified Objects

Hi there,

Question: I am looking to convert the following data structure:

 console.log(convertCoordinates([
    { "name": "Salvador",       "coordinates": ["-23.6821604","-46.8754915"]},
    { "name": "Brasília",  "coordinates": ["-22.9137531","-73.5860657"]},
    { "name": "Recife",          "coordinates": [ "-8.0462741","-35.0000824"]}
  ]));

into this format?

{ 
  '0':
   { name: 'Salvador',
     coordinates: [-46.8755, -23.6822 ] },
  '1':
   { name: 'Brasília',
     coordinates: [-73.5861, -22.9137] },
  '2': { name: 'Recife', 
          coordinates: [-35.0001, -8.0463] }
}

Differences between the two results.

First Format:
- is an array of objects
- Contains city names and coordinates as string arrays.

Second Format:
- is a single object - Contains city names (same as in the first format) and coordinates as decimal numbers with 4 digits after the dot; - The positions of longitude and latitude are swapped - longitude comes first.

Language: JavaScript

I attempted to use the ** Object.assign ** method but couldn't achieve the desired changes with the "coordinates".

function convertCoordinates(array){

    let obj = Object.assign({},array);

    return obj;
  }

  // Test
  console.log(convertCoordinates([
    { "name": "Salvador",       "coordinates": ["-23.6821604","-46.8754915"]},
    { "name": "Brasília",  "coordinates": ["-22.9137531","-73.5860657"]},
    { "name": "Recife",          "coordinates": [ "-8.0462741","-35.0000824"]}
  ]));

Can someone provide assistance with this function puzzle?

Answer №1

To streamline the process, you can use the reduce method to convert the coordinates into an object with each iteration:

const strToFixed4 = str => Number(str).toFixed(4);
const prepareCoordinates = (array) => array.reduce(
  (accum, { name, coordinates: [lat, lng] }, i) => (
    {
      ...accum,
      [i]: { name, coordinates: [strToFixed4(lng), strToFixed4(lat)] }
    }),
  {}
);

console.log(prepareCoordinates([
  { "name": "Salvador",       "coordinates": ["-23.6821604","-46.8754915"]},
  { "name": "Brasília",  "coordinates": ["-22.9137531","-73.5860657"]},
  { "name": "Recife",          "coordinates": [ "-8.0462741","-35.0000824"]}
]));

Answer №2

function convertCoords(array){
    let objs = {...array}; //using es6 spread operator to clone array
    for (index in objs) { //loop through each object in the array
        objs[index].coordinates.forEach(coord => Number(coord)); //convert each coordinate in coordinates array to number
    }
    return objs;
  }

The es6 spread operator simplifies the process, similar to object.assign() but with a cleaner syntax.

I believe this function will provide the expected outcome, feel free to ask if you have any questions.

Answer №3

Here is the ultimate solution folks! Shoutout to both of you!

const prepareCoordinates = (array) => array.reduce(
  (accum, { name, coordinates: [lat, lng] }, i) => (
    {
      ...accum,
      [i]: { name, coordinates: [Number(parseFloat(lng).toFixed(4)), Number(parseFloat(lat).toFixed(4))] }
    }),
  {}
);

console.log(prepareCoordinates([
  { "name": "São Paulo",       "coordinates": ["-23.6821604","-46.8754915"]},
  { "name": "Rio de Janeiro",  "coordinates": ["-22.9137531","-73.5860657"]},
  { "name": "Recife",          "coordinates": [ "-8.0462741","-35.0000824"]}
]));

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 HTML function transforms blank spaces into the symbol "+"

Just starting out with a question: I created a basic submission form, but I noticed that if there are any spaces in the inputs, the values get changed to a plus sign (+). Here's my form: <form name="input" action="search" method="get"> Web Ad ...

Tips for transferring JSON data to a CodeIgniter view

I have a query regarding how to replace a specific section of my webpage with data returned from the controller. Currently, I have a page that displays movie details directly fetched from the database. My goal is to only display movies of a particular genr ...

What is the process for mapping an object in order to alter it?

Is there a way to map an object and replace empty values with null? obj={a:'',b:firstname,c:'',d:lastname} I want the result to look like this, replacing empty values with null: obj={a:null,b:firstname,c:null,d:lastname}. Any sugges ...

Create an if statement that depends on the current URL without explicitly mentioning it

I am currently working on a project to display specific RSS feeds based on the current URL. I have made some progress with my solution below, but I am looking for a way to dynamically check the current URL and pull the corresponding RSS feed instead of spe ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

Divide the string by spaces

One of the challenges I am facing involves a textarea where users can input messages. The goal is to split the message into an array of words after detecting an '@' symbol, and then search for specific words in that array such as @person1 and @pe ...

What methods are available for updating the href color of an element using the DOM?

I am looking to update the color of a tab (Mathematics-tab) based on the value of 'aria-selected' changing to true in Bootstrap. I have multiple tabs, including one for mathematics, and I want to visually differentiate between selected and unsele ...

Having trouble with deploying Node.js to Heroku? Feel like your 'git push her

After successfully running my app locally, I encountered an issue when trying to deploy it to Heroku. The deployment process just hangs indefinitely and only displays one public file on the website with an error message stating: "https://analogy-alley.hero ...

Having a strange glitch when creating a discord bot. Any suggestions on how to get it up and running smoothly?

Each time I attempt to launch my Discord bot, an error pops up in PowerShell. C:\Users\alexa\Desktop\WHA Period Bot\index.js:1 c SyntaxError: Invalid or unexpected token at Module._compile (internal/modules/cjs/loader.js:891: ...

Text Overlapping Issue in React Material UI Components

I am currently working on a React application using Material UI and facing an issue while implementing an entity update page. The task at hand is to display the existing values of the entity for the user to update. To achieve this, I have set the default v ...

Activate the class when clicked

I am facing a minor issue with the JavaScript onClick function. I need a function that will target a specific class, like .modal. Currently, it looks like this <div class="modal" onclick="modalFix()"> <p>here is some text</p> </div> ...

Is it possible to transfer the data from an array into a pointer for storage?

I'm currently working on a program that generates results similar to the ls -l command. I have successfully implemented loops to produce these results, but now I aim to store specific variables in a linked list for future sorting using a lexical-graph ...

Selenium gets caught in endless loops

On my homepage, I have a variety of links that lead to different applications. Each link opens a new tab or window, where I need to check for the presence of a specific element using its XPath (which is provided from an Excel file for all applications). ...

What is the best method to center a div on the screen?

Is there a way to have a div open in the center of the screen? ...

Numerous calls for the same event

When calling two functions on the same event onChange, I noticed that the second one doesn't execute this.updateValue. As a result, the value of the input doesn't change. However, after removing the first call and changing it to onChange={this.up ...

Difficulty encountered in generating an array of JSON entities

So, I am tasked with creating an array of JSON objects in a specific format: [object, object, object...] To achieve this, I iterate through all the selected rows in my jQuery jtable, consolidating all parameters for each row into a single object. After r ...

What is the best way to transfer data from a JavaScript function to the C# code behind?

I am trying to work with a dynamic button that has unique ids. When the button is clicked, I need to pass the id to my btnDetails_Click event in C# or store it in a variable for efficiency. Here's what I have so far: $("button").click(function() { ...

Compensating for the variations in camera rotation specifications between standard and virtual reality mode within the aframe framework

I'm currently developing a WebVR project using Aframe that features multiple miniature 3D scenes (approximately eight) surrounding the viewer. To view each scene, users must rotate their viewpoint accordingly. Since the number of scenes surpasses wha ...

When dynamically adding an option, the select value becomes empty

I am facing a problem with a select element that I cannot change programmatically. Initially, the select has only one option: The initial HTML structure looks like this: <select id="clients" name="client"> <option>Existing Clients...</ ...

Tips for organizing a massive text file into a multi-dimensional array?

I'm attempting to read and organize a large text file into a 3D array using Scanner(), but I'm encountering issues with populating the array and consistently coming across the error java.lang.NullPointerException. I suspect there are additional p ...