Guide on extracting data from a specific column in an object and converting it into a list using JavaScript

Imagine we are working with the following JSON information

var example = [{
    latitude: 11.1111,
    longitude: 111.111,
    name: "for example1",
    altitude: 88
},
{
    latitude: 22.2222,
    longitude: 222.222,
    name: "for example2",
    altitude: 89
},
{
    latitude: 33.3333,
    longitude: 333.333,
    name: "for example3",
    altitude: 90
}
]

I am looking to extract only the latitude and longitude data from the list or object provided, as my Map API in my react-native application specifically requires this information. Due to performance concerns, I cannot use a loop to achieve this. While querying a database like MySQL separately could solve this problem, I am hesitant to take this approach as it may not be ideal. (I would appreciate any alternate suggestions if available)


Thank you for taking the time to read this. How would you recommend solving this issue?

Answer №1

Here's a solution for you. It creates a fresh array containing only latitude and longitude properties from objects.

const filteredArray = originalArray.map(item => {
    return {
        lat: item.lat,
        long: item.long
    }  
})

Answer №2

sample.map(element => ('lat' && 'lon') in element && element);

Answer №3

Transforming the data from example using ES6 arrow functions: example.map(({latitude, longitude}) => ({latitude, longitude}))

Necessitated by the Map API in my react-native application.

Would an iterator solution suffice?

[edit]

Creating a generator function to transform the data in 'example' object:
const projected = ( function* () {
  for (record of example) yield {
    latitude:  record.latitude,
    longitude: record.longitude,
  };
})()

Answer №4

It seems like you are attempting to store all the filtered data in your database. Is that correct? If so, one approach could be to map or loop through the data first as follows ->

const filteredData = example.map(({latitude, longitude}) => ({latitude, longitude}));

Afterwards, you can bulk insert into your MySQL database. Here is an example of how you can do this ->

INSERT INTO tbl_name(col1, col2, col3) VALUES(val1, val2, val3), (val4, val5, val6), (val7, val8, val9);

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

Leveraging the Wikia API

I've been attempting to utilize the X-men API on Wikia in order to gather the name and image of each character for use in a single page application using JavaScript. You can find the link to the wiki page here: Despite my efforts, I am struggling to ...

What is the best way to assign a specific attribute to just one type within a hierarchy of inherited classes?

While addressing my specific issue with the JSON.NET library, I have come across a larger problem that needs to be resolved. I am attempting to deserialize a complex JSON type to a .NET object model with an inheritance tree using JSON.NET. The challenge l ...

Transform a traditional class component into a functional component

Is there a way to successfully convert this class component into a function component despite my previous failed attempts? componentDidMount(){ const id = this.props.match.params.id; getById( parseInt(id) ) .then(product => { this.setS ...

Mastering the Art of Integrating API and JSON!

I've developed a bot using botkit and the Zendesk API to retrieve information. There's a function in my bot that prompts the user for a search term, searches for relevant information using the Zendesk API, and displays the result. I'm faci ...

Struggling with continuously re-rendering a color background when using useMemo in React?

After every re-render, a new color is generated. Is there a way to store the initial color and reuse it in subsequent renders? const initialColor = generateNewColor(); // some random color const backgroundColor = React.useMemo(() => { return ...

I need help with customizing the progress bar in HTML and CSS

How can I create a progress bar like the one shown below: .detail-load { height: 42px; border: 1px solid #A2B2C5; padding: 1px; border-radius: 10px; } .detail-load > .detail-loading { background: #904BFF; height ...

"Uncaught ReferenceError: $ is not defined in a JavaScript/Vue.js

Currently, I am working on the javascript/vue.js page found at this link. In this file, I have added the following code: $(document).ready(function() { myIP(); }); function myIP() { $.getJSON("//freegeoip.net/json/?callback=?", function(data) { / ...

Angular2's change detection mechanism does not behave as anticipated after receiving a message from a Worker

Within my angular2 application, I encountered a rather intriguing scenario which I will simplify here. This is AppComponnet export class AppComponent { tabs: any = []; viewModes = [ { label: "List View"}, { label: "Tree View" }, ...

Angular 4 encounters performance issues when rendering numerous base64 images simultaneously

I'm currently working on a private project that involves using Angular 4 (specifically version 4.1.2). One issue we're facing is related to rendering multiple base64 images on an HTML page. The performance of the application significantly drops w ...

Organize the JSON formatting in cakePHP for optimal output

What is the most effective way to customize the JSON output in cakephp 2.x? Here is the code snippet from my controller: $questions = $this->Question->find('threaded', array( 'fields' => array( 'label', &a ...

Automatically shutting windows using jQuery after a certain number of seconds

I am currently trying to find a solution to this issue. The problem I am facing is that I need to close a window after it has been open for 7 seconds each time. I have managed to make the windows close using SetInterval, however, the timing is not precise ...

Tips for accessing information from an Angular Resource promise

I am currently facing an issue when trying to read data from an angular promise that was returned. Before, I had the following code: var data = category.get({id:userid}); Later, I realized that the data being returned was an unresolved promise. So, I ma ...

Creating dynamic rows for Firebase data in React BootstrapTable can be accomplished by dynamically rendering each row

Hey everyone, I'm currently working on a web app project where I am creating a table. Below is the code snippet for it: class Table1 extends Component { render() { return ( <div> <BootstrapTable data={this.props.data}> ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

What are the various ways to display time zone in a different format?

I need to display the timezone in a unique manner. I have captured the user's timezone in a variable called timeZone, which currently returns the value as Asia/Calcutta. console.log(timeZone) // "Asia/Calcutta" Is there a way to showcase the timezon ...

The latest version of Spring MVC, 4.1.x, is encountering a "Not Acceptable" error while trying

After creating a Rest Service using Spring MVC4.1.X, I encountered an issue when attempting to return Json output to the browser. The error message displayed was: The resource identified by this request is only capable of generating responses with charact ...

Outputting a variable using javascript

My challenge is to efficiently print the contract variable, which contains HTML content fetched from the server. How can I achieve this easily? I want the print window in Chrome to display the document with the contents of my variable when I click a button ...

What could be causing the Uncaught ReferenceError message that says scrollToM is not defined in my code?

Can someone help me with this code for creating a single page website? $(window).load(function() { function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') ...

Retrieve data from Json array

Hello everyone, After requesting a list of users, I received the following JSON response. I need to extract the id of a specific user based on their username. For example, if I need the id of the user "Test1", how can I achieve that? Any assistance would ...

Checking with Protractor to see if the modal is displayed

I am currently working on a Protractor test to check if a bootstrap modal window that confirms the deletion of a record is visible at this time. The record that needs to be deleted is displayed in an angular ng-repeat, so I have to trigger the delete butt ...