Develop an Array Using JavaScript

I have an array of markers for Google Maps that is structured like this:

markers: [{
    position: {
        lat: 37.0636782,
        lng: -8.0288746
    },
    infoText: 'Marker 1'
}],

In addition, I have data retrieved from my CMS in the following format:

[{
    "latitude": "37.0636782", 
    "longitude": "-8.0288746", 
    "info_snippet": "test123"
},
{
    "latitude": "37.0636789", 
    "longitude": "-8.0288745", 
    "info_snippet": "test111"
}]

My goal is to transform the second array to match the structure of the first array. Is this achievable?

Below is the loop I've implemented for this task.

this.pins = response.data.acf.map_markers;
let self = this;
this.pins.forEach(function(item) {
    self.markers.position.lat.push(item.latitude);
    self.markers.position.lng.push(item.longitude);
    self.markers.infoText.push(item.info_snippet);
})

Answer №1

When working with your original map, it's important to customize the keys according to your needs. Here is an example of how you can achieve this:

this.locations = response.data.acf.map_markers;

this.locations.map(({latitude, longitude, info_snippet}) => ({
  position: { lat: latitude, lng: longitude },
  information: info_snippet
}));

const coordinates = [{
    "latitude": "37.0636782",
    "longitude": "-8.0288746",
    "info_snippet": "test123"
  },
  {
    "latitude": "37.0636789",
    "longitude": "-8.0288745",
    "info_snippet": "test111"
  }
];

const newCoordinates = coordinates.map(({latitude, longitude, info_snippet}) => ({
  position: { lat: latitude, lng: longitude },
  information: info_snippet
}));

console.log(newCoordinates);

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

What aspects of MongoDB security am I overlooking?

Is it a secure way to connect to Mongo DB by using Node JS, Mongo DB, and Express? Could someone provide an explanation of this code in terms of security? === Many tutorials often only show... var mongoClient = new MongoClient(new Server('localhos ...

I am looking to manage user-related data in the comment model using mongoose and express

I have a user, post, and comment modal This is my comment modal import mongoose from "mongoose"; const CommentSchema = new mongoose.Schema({ postId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", }, userId: { t ...

Is there a way to "redirect" the user during the onbeforeunload event? If not, what is the alternative method to achieve this?

Can the browser be redirected to another page upon closing? Various Methods Tried: Attempted using onunload, but unsuccessful window.onunload = function redirect(){...} Another method tested, also unsuccessful: window.onbeforeunload = redirect(){ ...

The functionality of Jasmine spyOn is not fully compatible with Angular crubbins

spyOn(service, someMethod).and.callThrough(); then... var an_object = some_objects[0]; useADirectiveThatRepeatsOver(some_objects); expect(service.someMethod).toHaveBeenCalledWith(an_object); fails with Expected spy someMethod to have been called with ...

Prevent automatic sliding in Bootstrap 4 carousel with the 'slide.bs.carousel' event

My goal is to implement a bootstrap4 carousel with two distinct steps: The first carousel item focuses on authentication, prompting for a username and password. In the second step, authorization takes place where the user must select from a list of acces ...

Unending Jquery Loop Iteration

I encountered a bug while writing code to display JSON data in an HTML table. Even though I only have 25 IDs to print from the JSON, my code is printing them more than 10 times when it should run only once. I tried adding breakpoints in the code but still ...

Utilizing Promises in the apply function

I am currently working on a project in Node.js that utilizes bluebird for promise handling, as well as ES6 native promises. In both projects, I have a chain where I make a database query structured like this: some_function(/*...*/) .then(function () ...

NG0303: Unable to establish a connection with 'ngbTooltip' as it is not recognized as a valid property of 'button'

ERROR: 'NG0303: Can't bind to 'ngbTooltip' since it isn't a known property of 'button'.' Encountering this issue in my Angular 12 project when running local tests, the ngbTooltip error is present in all .spec files. ...

What is preventing you from utilizing JavaScript or jQuery to showcase a dropdown menu?

As a JavaScript novice, I find myself wondering about the following issue. I've seen it pop up numerous times on Stack Overflow. Can JS be leveraged to unveil an HTML select element and display its list of options? How can you instruct an HTML SELECT ...

How to include arrays of images into a single array with Numpy

I am facing an issue while creating an array of images with Numpy for an image classification neural network. When I convert the image into an array, it becomes 3 dimensions. However, after using np.append to add it to my array of all images, the shape tur ...

Error: (3) Invalid range specified for column 3 during globbing operation

When attempting to index a basic JSON data in Solr using curl, I encountered an error message. Here is the command I used: "curl -X POST -H 'Content-Type:application/json'-d http://localhost:8983/solr/informationretrieval/update/json/docs ' ...

Troubleshoot: How to Fix the socket.io net::ERR_CONNECTION_TIMED_OUT

I am facing an issue with my website's real-time chat functionality. It works perfectly on localhost without any errors. However, when I try to run it on the server, I encounter the following error: http://my.domain:52398/socket.io/?EIO=3&transpo ...

Updating form fields within nested forms using the FormBuilder array

The recommended method to change nested values according to the API documentation is using patchValue. For example, myForm.patchValue({'key': {'subKey': 'newValue'}}); But what if we need to change values in a nested array, ...

There is a lack of definition for an HTML form element in JavaScript

Encountering an issue with a HTML form that has 4 text inputs, where submitting it to a Javascript function results in the first 3 inputs working correctly, but the fourth being undefined. Highlighted code snippet: The HTML section: <form action="inse ...

Server side processes automatically converting boolean parameters in Axios get requests to strings

My code involves a JSON object being passed as parameters to the Axios GET API. Here is the JSON object: obj = { name: "device" value: true, } The Axios GET request is made with the above object like this - tableFilter = (obj) => { ...

How do I utilize Ajax to compare the value selected from a drop down menu in a form with entries in my database, and retrieve the corresponding record/row to automatically fill in a form?

I have a drop-down menu where users can select an option. I need to match the selected value with the corresponding record in my database under the "invoiceid" column, and then populate a form with the associated data when a prefill button is clicked. Belo ...

Struggling to send data to Wufoo API using PHP and AJAX

I'm still getting the hang of PHP and attempting to send data to a Wufoo Form that includes the fields shown below: https://i.sstatic.net/yoOgy.png However, when trying to POST information to it, I keep receiving a 500: Internal Server Error along w ...

In C#, extract a specific line from JSON data by deserializing it

I am attempting to extract a specific line and its elements from this JSON API. The URL for the API is: This is the data that will be returned: { "server_time": 1424431698, "pairs": { "btc_usd": { "decimal_places": 3, ...

What could be causing the lack of functionality for my button click in my JavaScript and HTML setup?

Currently, I am attempting to implement a functionality where I have two buttons at the top of my page. One button displays "French" by default, and when I click on the "English" button, it should replace the text with "French" using show and hide methods. ...

Using JQuery to emphasize selected radio button area

Can someone help me modify the code to highlight the checked radio button by adding or removing a class from the <span class " ui-message ui-state-highlight"> element? Below is the HTML and JS code: $(document).ready(function(){ $('# ...