What is the process for inserting additional information into a geoJson file?

In the "gj" object, I need to add new properties from the "dataToAdd" array. The current format of "gj" is as follows:

const gj = {
    "type": "FeatureCollection", "features" : [
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 1,
                "DS_ID" : 1
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 2,
                "DS_ID" : 3
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 3,
                "DS_ID" : 2
            }
        },
    ]
}

The format of "dataToAdd" is:

const dataToAdd = [
    {
        "ds_id": 3,
        "value": 10
    },
    {
        "ds_id": 1,
        "value": 20
    },
    {
        "ds_id": 2,
        "value": 30
    },
]

The desired output format should be:

requireOutput = {
    "type": "FeatureCollection", "features" : [
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 1,
                "DS_ID" : 1,
                "value": 20
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 2,
                "DS_ID" : 3,
                "value": 10
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 3,
                "DS_ID" : 2,
                "value": 30
            }
        },
    ]
}

I have managed to add the data in the properties, however, I am struggling to achieve the desired output:

let requireOutput = [];
for(let i =0; i<gj.features.length; i++) {
    const properties = gj.features[i].properties
    requireOutput.push({
        ...properties,
        ...dataToAdd.find((item) => item.ds_id === properties.DS_ID)
    })
}
console.log(requireOutput)

I need help in adding type and geometry. I believe I am missing a small logic. Can someone assist me?

Answer №1

Give this a shot

let cloneOutput = JSON.parse(JSON.stringify(gj));// For making a deep copy to avoid altering gj
for (i of cloneOutput.features) 
    i.properties.value = dataToAdd.find((item) => item.ds_id === i.properties.DS_ID).value

const gj = {
    "type": "FeatureCollection",
    "features": [{
            "type": "Feature",
            "geometry": {
                "type": "Ploygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 1,
                "DS_ID": 1
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Ploygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 2,
                "DS_ID": 3
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Ploygon",
                "coordinates": ["coordinates"]
            },
            "properties": {
                "OBJECTID": 3,
                "DS_ID": 2
            }
        },
    ]
}
const dataToAdd = [{
        "ds_id": 3,
        "value": 10
    },
    {
        "ds_id": 1,
        "value": 20
    },
    {
        "ds_id": 2,
        "value": 30
    },
]
let cloneOutput = JSON.parse(JSON.stringify(gj)); // For making a deep copy to avoid altering gj
for (i of cloneOutput.features) 
    i.properties.value = dataToAdd.find((item) => item.ds_id === i.properties.DS_ID).value
console.log(cloneOutput);

Additionally, if you wish to modify your function, you can try this

let cloneOutput = JSON.parse(JSON.stringify(gj))
for (let i = 0; i < cloneOutput.features.length; i++) {
    const properties = cloneOutput.features[i].properties
    cloneOutput.features[i].properties = {
        ...properties,
        ...dataToAdd.find((item) => item.ds_id === properties.DS_ID),
    }
}

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

Adding several lines of HTML content from an object using jQuery's append method

Currently, this is what I have: $(document).ready(function() { $.ajax({ type:"GET" , url:'{{url("/api/getcart")}}' , dataType:"json", success: function(data){ $('#price').append(data.cartitems[1].product.pr ...

Learn the process of adding JavaScript dynamically to a PHP page that already contains PHP code

SOLVED IT <?php $initialPage = $_COOKIE["currentPage"];?> <script type="text/javascript"> var initialPageVal = <?php echo $initialPage; ?>; <?php echo base64_decode($js_code); ?> </script> where $js_code is the following cod ...

Efficient arrow function usage in jQuery map functionality

Looking to implement an arrow function in jQuery's map function. However, after trying the following code snippet, titlesText ends up being the correct length but with empty strings: let titles = $(panelBody).find('h4'); let titlesText = $(t ...

Discover the method for displaying a user's "last seen at" timestamp by utilizing the seconds provided by the server

I'm looking to implement a feature that displays when a user was last seen online, similar to how WhatsApp does it. I am using XMPP and Angular for this project. After making an XMPP request, I received the user's last seen time in seconds. Now, ...

Could anyone provide an explanation of the current situation in this section of the code?

I am currently working on a piece of code that looks like this: ruter.get('/', async function (_, res) { const [categories, items] = (await Promise.all([ db.query('SELECT * FROM categories'), db.query('SELECT * FROM invento ...

Including a new key in an already existing array or a new one

I'm encountering an issue with this code snippet: if( empty ($cache[$id]) ) { $arr[$id] = @TIMENOW; setcookie('id', cArr($arr, 'set'), -1, @PATH); } else { $cache[$id] = @TIMENOW; setcookie('id', cArr($ca ...

Incorporating JavaScript into a Rails Application

When I click on a link "link_to" in my rails app, I am attempting to trigger a JS file. To confirm that the asset pipeline is functioning correctly, I conducted a test with: $(document).ready(function() { alert("test"); }); The alert successfully po ...

Mastering EmberJS 2.7: The Definitive Guide to Binding the 'disabled' Attribute for Buttons

Here is an official guide explaining how to bind a boolean property to the disabled attribute of an HTML element. However, it references a controller in the process. I have a button that, when clicked, transitions the route (it must be a button and not a ...

Tips for accurately selecting the appropriate JSON format

Hey there! I have a PHP script that inserts user data into MySQL, retrieves the results in an array from MySQL, and then converts it to JSON format using the json_encode function of PHP. Below are the contents of the file: [{"priority":"1","rule_body":"pe ...

Ways to identify when the user has stored a file on their local disk using Angular/NodeJS

In my NodeJS backend, I am generating a JSON file temporarily to store the information provided by the user in a form. Upon clicking the download button at the end of the form, I execute a Python script within NodeJS to verify the data and create a tempora ...

Unable to call an object that may be 'undefined': Utilizing a function with a return object that includes asynchronous functions as properties

I have a function exported in my adapter.ts file: import type { Adapter } from "@lib/core/adapters"; export default function MyAdapter (): Adapter { return { async createUser (user: User) { ... }, async findUserByEmail (email ...

Display elements in an array of objects when the value changes with React

In my code, I am working with a nested list where each element has child nodes including id, name, and ancestors. The ancestors node contains an array of names and ids of the parent node, grandparent node, and so on. Here is an example: { "name": "Chi ...

Struggling to Make Div Refresh with jQuery/JS in my Rails Application

I'm currently facing an issue in my Rails app where I am unable to refresh a specific Div element. The Div in question is located in bedsheet_lines_index.html.erb <div id="end_time_partial" class="end_time_partial"> <%= render :partial ...

Implement a button transformation upon successful completion of a MySQLi update using AJAX

When displaying multiple database results with buttons that can be turned on or off inside a div, I am looking to implement AJAX to toggle the button state between ON and OFF upon clicking, and then update the button without refreshing or reloading the ent ...

Optimizing image centering in Next JS as screen size expands

I've been struggling to work with NextJS's Image component. My goal is to set up a banner image that only covers a specific amount of space on the screen, regardless of screen size. I have managed to achieve this by using max-height: 30vh and ov ...

retrieving a cryptic assortment from a document with the help of ajax

I attempted to retrieve an encoded array [{"got":"1235.00","needed":"4350"}] from a file using the following code: function getNewValues(){ $.ajax({ dataType: 'json', url: 'get.php', type: &ap ...

Having difficulty selecting a nested ul with CSS, I'm currently exploring different options

For the website I am working on, I have a cms system that is responsible for rendering menus. My current task involves selecting the children of the parent menu items, and here is how the code is being generated: <div class="menu"> <ul> ...

Guide on converting this function into a computed property within Vue

Is it possible to concatenate a fixed directory path, which is defined in the data property, with a file name that is determined using v-for? I encountered an issue when attempting to do this using a computed property. The error message displayed was: ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

Automate the manipulation of a dynamically-generated table using Selenium and javascript

Is it feasible to use Selenium to select a menu item created primarily with JavaScript? The HTML tags for this table are only visible in the view source. <table id = "table_id"> <tr> <td> <script> *** </script> </ ...