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

Next.js encountered an issue: React.Children.only function was expecting to receive only one React element child, but received more

I have created a component named Nav located in the components directory. Here is the code for it: import Link from 'next/link'; const Nav = () => { return( <div> <Link href="/"> <a> Home </a> ...

Access a folder in JavaScript using Flask

I need to specify a directory in a script. $images_dir = '{{url_for('.../pictures')}}'; In my flask application directory structure, it looks like this: Root -wep.py -templates -gallery.html -static -pictures The images are stored ...

Issue with reCAPTCHA callback in Firebase Phone Authentication not functioning as expected

I have been working on integrating phone authentication into my NextJS website. I added the reCAPTCHA code within my useEffect, but for some reason, it does not get triggered when the button with the specified id is clicked. Surprisingly, there are no erro ...

Exploring AngularJS Navigation in Windows 8 App Store Applications

Hello, I recently started learning about developing Windows Store apps. I found a way to incorporate AngularJS into my Windows 8 store app by making some adjustments in the AngularJS library. However, I'm now struggling with implementing AngularJS rou ...

Displaying a div when a radio button is clicked in React

I am attempting to create a functionality where clicking on one radio button will display another div in React. As a beginner in React, I have tried implementing the code below but encountered issues with hiding and displaying the content based on user inp ...

How does gray-matter function in Node.js affect the matter within?

import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; const postsDirectory = path.join(process.cwd(), 'posts'); // ... ... ... // export function getPostData(id) { const fullPath = ...

PHP: In search of an optimal method to iterate through arrays to find matching elements

I am faced with the challenge of efficiently looping through multiple arrays of strings to find a match and if found, exit the loop. Currently, I am using separate loops for each array, but I believe there must be a more streamlined approach that avoids re ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

Modify an HTML table and record any modifications as POST requests using Javascript

As a beginner in JavaScript and HTML, I am open to corrections if I am not following the correct practices. Recently, I delved into editing an HTML form table. {%extends 'base.html'%} {%block content%} <html> <body> <h4> Search ...

Analyzing the network requests of a specified URL with Python programming

In my Python program, I am trying to fetch the URL highlighted in red which changes daily. The only constant URL I have is the one highlighted in green. However, the GET parameters like token, qid, or callback also change frequently, making it impossible f ...

What could be causing my Node application to give a 404 error when making a POST request?

I'm at a loss trying to debug my app for what seems like a simple error, but I just can't locate it. Here is an overview of how my Express app is structured. My routes are set up as follows: var routes = require('./routes'); ... app.g ...

Issues with FullCalendar functionality in CakePHP 1.2.5 are arising when using jQuery version 1.4.1

Currently, I am encountering an issue with fetching events data through a URL that returns JSON data. Surprisingly, the code works flawlessly with jQuery 1.3.2, however, it throws errors when using jQuery 1.4.1. The specific error message displayed in the ...

Executing program through Socket.io alert

My NodeJS server sends notifications to clients when certain actions are performed, such as deleting a row from a grid. Socket.io broadcasts this information to all connected clients. In the example of deleting a row, one approach could be adding an `acti ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

Refresh the content with an embedded iframe

I am attempting to update the body content by removing all existing content and inserting an iframe: function create_custom_iframe(target){ var iframe = document.createElement('iframe'); iframe.setAttribute('id', 'target_u ...

Is it more advantageous to create two distinct projects for the frontend and backend along with an API, or should I consolidate them into a

Asking for some guidance on a few queries I have. I've developed a backend node server with express & mongo to run specific tasks and store them in the database, along with creating an admin page using express & bootstrap. Everything is functioning s ...

Is it possible to capture a submit event from a form within an iframe using jQuery or JavaScript

If I have a webpage with an embedded iframe containing a form, how can I update a hidden field value on the main page once the form is submitted? What is the best way to trigger an event in the parent page upon form submission? Here's a simplified ex ...

PHP's json_encode() compared to using an empty NSDictionary in iOS development

I have a question regarding how to handle JSON encoding/decoding in PHP without converting arrays or dictionaries. In my iOS app, I store data in an NSDictionary. Some of this data is nested and includes NSArrays or other NSDictionarys that may contain fu ...

Is it advisable to send an object as an argument in a function?

Here's the code snippet I'm working with: const failure1 = false; const failure2 = false; function callbackFunction(callback, errorCallback) { if (failure1) { errorCallback({ name: 'Negative event1 occurred', ...

Animate the transition effect as soon as the block is displayed

Looking to create a smooth page transition using CSS changes with the help of Javascript (jQuery). Initially, one of the pages is set to display none. page1 = $('.page1'); page2 = $('.page2'); page1.removeClass('animate').cs ...