Tips for merging values from a json file with a geojson map file

I have a task at hand where I am aiming to merge a GeoJSON map file with pertinent key values from a JSON file in order to create a choropleth map.

Let's take a look at the structure of these files:

data1.json

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "STATE": "06",
                "ZIPCODE": "94601"
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [...]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "STATE": "06",
                "ZIPCODE": "94501"
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [...]
            }
        }
    ]
}

data2.json

{
    "94501": {
    "crime": 172,
    "income": 9456,
    },
    "94601": {
    "crime": 118,
    "income": 28097,
}

This is what I envision for the final combined object:

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "STATE": "06",
                "ZIPCODE": "94601",
                "crime": 118,
                "income": 28097
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [...]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "STATE": "06",
                "ZIPCODE": "94501",
                "crime": 172,
                "income": 9456
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [...]
            }
        }
    ]
}

Presently, my code appears as follows:

d3.json("data1.json", function (geoData) {
    d3.json("data2.json", function (zipdata) {

        var geoFeatures = geoData.features;

        for (var i = 0; i < geoFeatures.length; i++) {
            Object.keys(zipdata).forEach(function (key) {
                if (geoFeatures[i].properties.ZIPCODE == key) {
                    var combined = Object.assign({}, geoFeatures[i], zipdata[key]);
                    console.log(combined);
                }
            })
        }
    })
})

While this code gets me near to the desired outcome, my aim is to preserve the GeoJSON map format showcased in data1.json.

Answer №1

To iterate through the features array and cross-reference the `zipcode` values in the `data2` object, adding relevant properties to each element.

let mapData = {"type": "FeatureCollection","features": [{"type": "Feature","properties": {"STATE": "06","ZIPCODE": "94601"},"geometry": {"type": "Polygon","coordinates": "[...]"}},{"type": "Feature","properties": {"STATE": "06","ZIPCODE": "94501"},"geometry": {"type": "Polygon","coordinates": "[...]"}}]}

let data2 = {"94501": {"crime": 172,"income": 9456,},"94601": {"crime": 118,"income": 28097,}}

mapData.features.forEach(item => {
  let { properties } = item
  let newProperties = data2[properties.ZIPCODE]
  item.properties = { ...properties, ...newProperties }
})

console.log(mapData)

Answer №2

Give this a shot:

let data1 = {"type": "FeatureCollection","features": [{"type": "Feature","properties": {"STATE": "08","ZIPCODE": "85602"},"geometry": {"type": "Polygon","coordinates": "[...]"}},{"type": "Feature","properties": {"STATE": "09","ZIPCODE": "85701"},"geometry": {"type": "Polygon","coordinates": "[...]"}}]}

let data2 = {"85602": {"crime": 215,"income": 8809,},"85701": {"crime": 120,"income": 29056,}}

data1.features.map(res => Object.assign(res, {
properties: {
    ...res.properties,
    ...data2[res.properties.ZIPCODE]
}
}))

console.log(data1)

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

TypeScript is unable to locate the identifier 'async' within the code

While working with TypeScript, I encountered an error: [ts] Cannot find name 'async' Here is the code snippet causing the issue: async someAsyncCode() { let asyncFn = () => { return new Promise((resolve: Function) => { resolv ...

Issue with handling 'this' in submit function in Sencha touch/JavaScript not resolved

I am currently working on developing a form using Sencha Touch that is designed to allow users to enter text and conduct a job search on a website. While most of the functionality is in place, including the reset button, I encounter an error when attemptin ...

Filter the options in the Vue Multiselect component by using the filter() method

This component and API can be found at https://github.com/vueform/multiselect Event Attributes Description @search-change query, select$ Emitted after a character is typed. I am trying to access select$.filteredOptions methods: { inputQuery( ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

Ensuring form input validity in real-time using jQuery's keyup event

I've been working on a form where the user can fill in an input and press enter to move to the next field. Although I have managed to get the functionality to show the next div, I am facing issues with validation... // Moving to next div on Enter ...

Ways to insert data in angularjs

As I attempt to add data to a list using the addGroup function, I encounter a type-error. The error message reads: "TypeError: Cannot read property 'push' of undefined" at r.$scope.addGroup (main.js:7) at fn (eval at compile (angular ...

Apollo's MockedProvider failing to provide the correct data as expected

I created a function called useDecider that utilizes apollo's useQuery method. Here is the code: useDecider: import { useState } from 'react'; import { useQuery, gql } from '@apollo/client'; export const GET_DECIDER = gql` quer ...

Working with Java to parse non-strict JSON data that does not have keys enclosed in quotes

I am currently facing the challenge of parsing a string in JSON format where keys are not enclosed in quotes. While I have successfully parsed this string in Javascript, I am struggling to find a Java API that can assist me with parsing. The APIs I have at ...

Having trouble setting up the rootReducer using combineReducers

import { combineReducers } from 'redux'; import { reducers } from './reducers'; import { IAppAction } from './action'; import { routerReducer } from 'react-router-redux'; import { IAppState } from './state/app-s ...

Function "Contains" not Present in Object

Upon executing the code provided below, I encounter the following error message. An issue has arisen: Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours. Here is the snippet of my code: var i = 0; var tempF ...

Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to ...

Updating state in Redux from a different componentorModifying state

I'm currently learning about redux and I'm facing an issue with accessing the stored state (id) in my components. Specifically, I have a Footer component with a button that is supposed to modify the state in the Layout component. However, I am un ...

Simple Steps for Making a Get Request using Vuex in Vue.js

I'm trying to figure out how to store products in Vuex within my index component. import Vue from 'vue' import Vuex from 'vuex' import cart from "./modules/cart"; import createPersistedState from "vuex-persistedstate ...

Steps for authenticating with the Wigle API when making GET requests

I was attempting to access the Wigle API from a jupyter notebook using the code provided, but kept encountering an error message: HTTPError: 401 Client Error: Unauthorized for url: It seems like there might be an issue with the authentication process, ho ...

Access information stored in a specific directory within my database

My application is built using php and laravel. Within my database, there is a column called MsgBody which stores an array formatted like this: "MsgBody": [ { "MsgType": "TIMCustomElem", "MsgContent" ...

When a Typescript object contains a key without a corresponding value, what is its significance?

In my experience, I've come across typescript objects that are defined in the following way: const MyObj = { myVar1, name1: myVar2 } Can someone explain the purpose of this object? I know that there is a key-value ...

In order to modify the PHP code in the file, I will need to update the JSON output that is currently being generated

I am currently using PHP code to generate a JSON output, but I have encountered an issue where it's creating an array of arrays with the information. What I want is to eliminate one array and simply display the list of APIs that have been used along w ...

A guide on using jq to selectively narrow down an array of objects by examining the values within a nested array of strings

My json file is structured like this: [{ "path": "p1" "title": "t1" "tags": ["tags1"] }, { "path": "p2" "title": "t2" "tags": ["tags1", "tag2"] }, { "path": "p3" "title": "t3" "tags": ["tags2"] } ] and I want to use jq ...

Utilize the effectiveness of the Ajax Success Handler for retrieving a distinct JSON entity

One of the features I am currently using involves an Ajax command that enables me to query data from a local server. In order to ensure smooth execution, it is crucial for me to return a JSON object through the success handler. The specific structure of m ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...