Changing data structure in AngularJS array

I'm working with a basic JavaScript array:

$scope.myArray = [{ "coords" : { "lat" : 0, "long" : 0 } }, { "coords" : { "lat" : 1, "long" : 1 } }, { "coords" : { "lat" : 2, "long" : 2 }];

Next, I want to utilize the angular-google-maps module to display these points as paths on the screen.

<ui-gmap-google-map center='map.center' zoom='map.zoom'>
    <ui-gmap-polyline path="myArray" stroke="p.stroke" visible='p.visible' geodesic='p.geodesic' fit="false" editable="p.editable" draggable="p.draggable" icons='p.icons'>
    </ui-gmap-polyline>
</ui-gmap-google-map>

The ui-gmap-polyline directive, however, requires the path to be an array of positions in simple format like this:

$scope.myArray = [{ "lat" : 0, "long" : 0 }, { "lat" : 1, "long" : 1 }, { "lat" : 2, "long" : 2 }];

Is there an efficient way to convert my initial complex array into the format expected by ui-gmap-polyline? I was considering using a filter but unsure if it's the most effective approach. Any new elements added or changed in myArray should automatically update on the Google Map. Another option could be to watch for changes in myArray and generate a new array each time for mapping purposes, but I feel there might be a simpler solution that I am overlooking.

e.g.: path="myArray | filter:coords"
-> Can an array be filtered to only extract specific fields from each element?

Edit: Just to note, myArray is a synchronized $firebaseArray (). This array receives automatic updates from the Firebase API when changes occur in the backend (beyond my control).

Answer №1

You can utilize the map method

arr.map(function(item) { return item.coordinates; });

Check out this Demo

var arr = [{
  "coordinates": {
    "latitude": 0,
    "longitude": 0
  }
}, {
  "coordinates": {
    "latitude": 1,
    "longitude": 1
  }
}, {
  "coordinates": {
    "latitude": 2,
    "longitude": 2
  }
}];

arr = arr.map(function(item) {
  return item.coordinates;
});

console.log(arr);
document.getElementById('output').innerHTML = JSON.stringify(arr, null, 2);
<pre id="output"></pre>

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

Maintain the initial value using ko.mapping.fromJS

How can I prevent new data fetched from an AJAX call using ko.mapping.fromJS from replacing the existing data in my observableArray? I want to append the new data without losing the previous entries. function ViewModel() { var self = this; self. ...

Implementing the adding functionality within an ejs file

I'm currently working on a project that involves fetching data from an API using a simple JavaScript file upon clicking a button. Initially, everything was functioning properly when both the HTML file and JS file were in the same folder, and I could a ...

Utilize a dual-color gradient effect on separate words within the <li> element

I am attempting to display the fizz buzz function in an unordered list, with each word being a different color ('fizz'-- green, 'buzz'--blue) as shown here: https://i.sstatic.net/Yvdal.jpg I have successfully displayed "fizz" and "buz ...

Utilize Parse cloud code to navigate and interact with object relationships

I am currently in the process of developing a Parse cloud code function that will produce a similar outcome to a GET request on parse/classes/MyClass, but with the IDs of the relations included. While I have successfully implemented this for a single obje ...

Tips for adjusting the size of a textarea to perfectly fit within a table cell

I have a textarea displayed within an input in a table, but I am looking to resize it so that it completely fills the table cell up to the borders. Here is the logic: <textarea type="textarea" value="{{data.directRowNo}}" id = " ...

Sending data from an AngularJS app to Google App Engine using HTTP post

I'm facing a small issue where I am unable to successfully POST my data (comments) to the GAE datastore using angularjs. Can you please help me identify what's wrong with the following angularjs "post" or html code? ANGULAR: $scope.addComment = ...

What is the reason behind "readFile" consuming more memory than the actual length of the file being read?

I am facing an issue with memory consumption when handling a large number of log files in a directory containing around 300,000 files. It seems that there is a memory leak when I use the "readFile" method to read all these files. Below is an example of No ...

Endlessly scrolling text using CSS

Is it possible to create a continuous rolling text effect on an HTML page without any gaps, similar to a ticker tape display? For example, displaying "Hello World ... Hello World ... Hello World ... Hello World ..." continuously. I attempted using the CSS ...

A tutorial on making a POST request using axios in a React application

I am struggling with my JavaScript skills I need assistance with calling the following CURL command successfully: curl -X POST -H "Content-Type: application/json" -u john.doe:moqui -d "{\"firstName\":\"Hung&bso ...

I encountered an SyntaxError while working with Ionic. The error message reads: "Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>)."

Here's the code that is causing me trouble: this.http.get('http://localhost/....) .map((res) => res.json()) .subscribe(( this.navCtrl.push(OtpPage,{mobileno:this.mobile}); }, (err) => { console.log(err ...

JS problem with decreasing

Within a React component, I have implemented the following method: addWidget = (index) => { let endX = this.state.widgets.reduce((endX, w) => endX.w + w.w, 0) console.log(endX); if (endX === 12) endX = 0 this.setState({ wi ...

Confusion with query parameters across various Socket.IO namespaces

Having difficulties with query parameters in socket.io. On the Server Side: var io = require('socket.io')(server); io.of('/1').on('connection', function(socket){ console.log(socket.request._query['test']); }); io ...

Guide on changing the color of an input box based on the variable size in ReactJs!

I need help with a disabled input box that receives a variable x, which can be either < 1 or > 1. My goal is to change the background color to red if x > 1, green if x < 1, and grey if there's no value provided. Here is what I have attempt ...

The functionality of updating input values via jQuery AJAX in HTML response is currently not functioning as expected

Hello, I need some assistance. I'm encountering difficulty with jQuery in modifying HTML values that are dynamically inserted through an AJAX response. Here is the link to the JSFiddle. Below is the HTML on the page: <button id="test">test&l ...

Spacing issues with inline-block elements when dealing with a large quantity of items

Currently, I am tackling the JS/jQuery Project for The Odin Project and I am confident that my solution is working exceptionally well. However, the issue I am facing is that when dealing with larger amounts of elements (around 40-45 in JSFiddle and 50-52 ...

Is this included in the total number of reads?

Following my query with CollectionsGroup, I attempted to retrieve the information of the parent's parent like this: db.collectionGroup('teams').where('players', 'array-contains', currentUser.uid).get().then(function(snaps ...

The observable object fails to update the view in Knockout

I'm struggling with this error and need some assistance. I've been working on it for a while, but haven't made any progress. Any help would be greatly appreciated! Thanks! Error: VM4705 knockout-debug.js:3326 Uncaught ReferenceError: Unabl ...

JavaScript function is returning 'undefined' instead of an integer

My JavaScript/jQuery function is not functioning correctly and instead of returning an integer, it returns undefined. function __getLastSelectedCategory(table_id) { if ( jQuery('.categories_table[data-table-id="1"]').find('td.active&apo ...

Grant permission to access a website even when domain filtering is enabled

I recently created a basic web application that utilizes the YouTube API for performing search and displaying results. $.ajax({ url: 'http://gdata.youtube.com/feeds/mobile/videos?alt=json-in-script&q=' + q, dataType: 'jsonp&apos ...

Ways to display a US map using d3.js with state names positioned outside each state and pointing towards it

Currently, I am working with d3.js and d3-geo to create a map of the USA. My goal is to display the names of some states inside the state boundaries itself, while others should have their names positioned outside the map with lines pointing to the correspo ...