What is the method to generate an array of values using a single attribute in GeoJSON data?

Note: After reviewing some possible solutions mentioned in this thread, I found that .map is the perfect fit for what I need, which was not covered in the original post. Thomas's response below addresses my specific requirement.

In JavaScript, how can I create an array of values representing a specific property from each feature in a GeoJSON file? Essentially, how do I transform this:

['caiparinha','caucasian','margarita']

into this?

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "brasil",
        "beverage": "caiparinha"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -56.953125,
          -8.754794702435605
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "name": "russia",
        "beverage": "caucasian"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          39.0234375,
          57.136239319177434
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "name": "mexico",
        "beverage": "margarita"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -105.1171875,
          25.165173368663954
        ]
      }
    }
  ]
}

When dealing with CSV data, it's as simple as selecting/parsing a single column, but in GeoJSON, the properties (similar to columns) are deeply nested. I have struggled to achieve this using .map and would prefer to avoid looping if possible, although I'm open to any suggestions.

The goal is to extract distribution information linked to each "variable" associated with the features being mapped, similar to functionality discussed here.

Answer №1

Consider trying the following approach

var geoData = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "Brazil",
        "drink": "Caipirinha"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -56.953125,
          -8.754794702435605
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "name": "Russia",
        "drink": "White Russian"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          39.0234375,
          57.136239319177434
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "name": "Mexico",
        "drink": "Margarita"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -105.1171875,
          25.165173368663954
        ]
      }
    }
  ]
};

var result = geoData.features.map(function (element) {
  return element.properties.drink;
});

console.log(result);

If your GeoJSON is retrieved through an Ajax request as a string, you can convert it to an object using JSON.parse(yourGeoData)

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 is the method for a JavaScript program to determine if a global property name has been defined according to the ECMA-262 standard

Imagine creating a function called checkIfEcmaGlobal which would return true for recognized names of ECMA-262 globals. $ node > checkIfEcmaGlobal('Array') true > checkIfEcmaGlobal('process') false What approach could be taken to ...

Encountering a problem with Oracle 12c when attempting to retrieve a JSON value exceeding 11000 characters using JSON_VALUE

While executing the code below on Oracle 12c : DECLARE l_json clob; l_var varchar2(90); l_query clob; mypath clob; l_path_value varchar2(100); BEGIN SELECT json_column into l_json from my_table; SELECT path_colum ...

Should you opt for returning [something] or (nothing) in Javascript with ExpressJS?

Is there a distinct contrast between returning something and returning nothing? Let's take a look at an example: user.save(function(err){ if ( err && err.code !== 11000 ) { console.log(err); console.log(err.code); res.send(&apo ...

How can one transform a web-based application into a seamless full-screen desktop experience on a Mac?

"Which software can be utilized to enable a web application to display an icon on the desktop of a Mac computer, while also opening up the web application in a fully immersive full-screen mode that supports all the touch and gesture functionalities provi ...

JavaScript enables the deletion of a class

In HTML 2, I am able to show different statements based on the scenario. These statements are styled using the Bootstrap alert class. The goal is to ensure that when new data is sent, any old communication disappears without causing overload on the page. ...

Ways to toggle the visibility of a div with a click event?

I am working on a project where I have a list view of items. I want to implement a feature where when a user clicks on an item, a hidden div below it will appear with options like price, quantity, and other details. I am looking for guidance on how to achi ...

An ASMX web service encountering an unescaped double quote within a parameter while processing JSON data

Within my HTTP REQUEST, a valid JSON string is present with a double quote in the middle of the name "jo\"hn" escaped. This was captured by Fiddler Web Debugger. {"name":"firstName","value":"jo\"hn"}, It's important to note that the reques ...

Guide on utilizing popup box input to amend CSS (background color)

I'm looking for some guidance on JavaScript and CSS. Is there a way to create a popup box where users can input a color (any main primary color recognized by CSS) and then have the background color of the page change accordingly in an external styles ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

Navigate through the document object model and identify every pair of input boxes sequentially to build a JavaScript object

Incorporating a varied number of input boxes into a view based on selections made in a combo box. For instance, selecting '1' from the combo box results in two input boxes being added to the view. Choosing '2' adds four input boxes. Ea ...

Error encountered while trying to display a Jbuilder JSON object in JSON format

Currently, I am in the process of developing a student tracking website using RoR. Within my model, I have written the following code to construct json: self.as_json json = Jbuilder.new do |j| j.courses student_courses do |course| j.(course, : ...

What is causing it to give me 'undefined' as the result?

Trying to execute a script, test.al(); and within test.al, it calls getcrypt.php();. The php script is hosted on a webserver, and it is functioning properly. Here are the current scripts being used: JS var getcrypt = { php: function () { $.a ...

Django getJSON with jQuery causing sessionid cookie mismatch

Encountering a problem with getJSON where it is sending an incorrect value for Django's sessionid cookie. There is an API operating on port 8000. When accessing this URL: http://localhost:8000/api/accounts/banner, it returns a JSON document if there ...

What is the method to retrieve JSON data from a URL and showcase the content on a JavaScript page?

I am currently developing a custom MS Teams application and I am facing an issue with fetching JSON data from a URL to display its contents later. Unfortunately, the fetch operation is failing. My objective is to retrieve a list of data from a specified UR ...

sum inside the while loop

Below is the provided HTML: <form> <textarea id="input1"></textarea> <textarea id="input2"></textarea> <span></span> </form> The following JavaScript code is included: $("#input2").keyup{ var a = ...

Angular Script Linking

Hello there! I am currently attempting to add an HTML tag to my response message, but for some reason it isn't working as expected. Here is a snippet of my controller code (in case the API indicates that the account doesn't exist - see this scr ...

Unable to retrieve the status for the specified ID through the use of AJAX

When I click the button in my app, I want to see the order status. However, currently all statuses are being displayed in the first order row. PHP: <?php $query = mysqli_query($conn, "SELECT o.orderid,o.product,o.ddate,o.pdate,k.kalibariname,o.sta ...

Utilizing an array of objects without specified indexes

I am currently taking a class on factory workers and another one on factory products. While that's all good, I now want to develop a program in main() that prompts the user to input information about either a worker or a new product in the factory, us ...

Is there a method to prevent the json file from being constantly overwritten?

After running this code, I noticed that even when inputting a different userId, it still ends up overwriting the existing user instead of adding a new one as intended. const user = userId; const userObj = {[user]:valueX}; words.users = userObj; f ...

What is preventing me from being able to manipulate the data retrieved from this ajax request?

I've been attempting to make an ajax call to my json server on localhost:3000 in order to retrieve an object that I can manipulate and display on a webpage. However, no matter what I try, I just can't seem to console log the (data) so that I can ...