Categorizing JavaScript objects based on a shared value

I have a query that retrieves location-based data from my database. After performing the query, I receive a collection of objects (which I consolidate into a single object and use console.log() to inspect its contents).

Each object represents a user's entry that includes notes about a specific location:

It includes: store name, address, userID, notes.

Multiple users can visit the same location and write different notes. My goal is to display these locations on a Google Map using the JavaScript API, grouping them by location so that when a marker is clicked, all notes for that specific location are displayed.

My approach involves grouping the objects based on address, then plotting the markers and iterating through each address as follows:

for (var i = 0; i < rowCountVisits; i++) {
    var storelatlng = new google.maps.LatLng(
    parseFloat(result[2].latVisit[i]),
    parseFloat(result[2].lngVisit[i]));
    locationsObjVisits.push({
        storelatlng: storelatlng,
        vName: result[2].vName[i],
        address: result[2].locationVisit[i],
        date: result[2].dateVisit[i],
        notes: result[2].notes[i],
        usersName: result[2].user.thisName[i],
        thisColour: result[2].user.thisColour[i]
    });
}

Regarding the locationsObjVisits... I'm unsure how to proceed with it. Any suggestions?

Answer №1

To efficiently store the details of locations and visits, one approach is to utilize an object with array properties, with addresses serving as keys:

var locationsObjs = {};

for (var i = 0; i < rowCountVisits; i++) {
    var storelatlng = new google.maps.LatLng(
    parseFloat(result[2].latVisit[i]),
    parseFloat(result[2].lngVisit[i]));
    var address = result[2].locationVisit[i];

    locationsObjs[address] = locationsObjs[address] || [];
    locationObjs[address].push({
        storelatlng: storelatlng,
        vName: result[2].vName[i],
        address: address,
        date: result[2].dateVisit[i],
        notes: result[2].notes[i],
        usersName: result[2].user.thisName[i],
        thisColour: result[2].user.thisColour[i]
    });
}

This method organizes objects by address, allowing easy retrieval through the object using the address as a key. By looping through the keys in locationsObjs, a distinct list of addresses can be obtained:

for(var address in locationsObjs)
    if(locationsObjs.hasOwnProperty(address))
        // Utilize the address to plot markers.

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

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Verify whether the input includes a specific value or a different one

Can someone help me with a simple task of checking if a textarea contains the value "12" OR "34"? I have tried the code below but it doesn't seem to work. Any suggestions? function check() { if (V1.value == ('12' || '34')) { ...

Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component. <template> <input-text v-model="form.name" /&g ...

Combining the `vuex-typex` npm package's `dist/index.js` for optimal performance with Jest testing framework

I initially raised this question as an open issue on GitHub. My experience with Vue.js, Vuex, TypeScript, and vuex-typex has led me to encounter syntax errors during Jest testing. I am relatively new to working with Vue.js, TypeScript, and Jest. It is wo ...

Creating a dynamic div and populating it with data from various elements in separate xhtml files: a step-by-step guide

I am looking to dynamically add a div under the div tag with id "includedContent" in the code below. Additionally, I would like to modify the load method to accept an array of ids instead of a hardcoded Id(123) and display the data in the dynamically creat ...

Converting a 2D matrix into a stacked 3D array in the R programming

In my R programming, I am working with a dataframe called data, which has dimensions of 120000 rows by 5 columns. Each set of 300 lines represents a frame captured at different time intervals, totaling 400 frames in total. What I Tried I attempted to tr ...

What is the best way to transform a Map<string, boolean> into an array of objects with key-value pairs {key: string, value: boolean

I'm currently working on a React project that incorporates TypeScript, and I've successfully implemented dynamic permission creation on the user creation page by utilizing this particular code snippet. The permissions being used on the page are m ...

The issue of white space appearing in the first option of an AngularJS dropdown in Internet Explorer 11

<select id="selectIdentity" name="selectIdentity" required ng-trim="true" ng-change="changedValue(addUser.identityProvider)" ng-model="addUser.identityProvider" > <option value="" selected hidden /> <option ng-repeat="idprovid ...

``Is it possible to save a Timeout object in telegram-node-bot in order to control a timer's activation

I am in the process of implementing a timer for my Telegram bot. I have figured out how to start the timer, but I am struggling to find a way to stop it using a command. Below is the code snippet: class TimerController extends TelegramBaseController { s ...

Issue with Vue3 ref not reflecting changes made to the array

When attempting to update an array that utilizes Vue's "ref", I encounter a specific issue. Below is a snippet of the code I'm working with: <script setup> import { ref } from 'vue'; let arr = ref([]); function updateArray(val) ...

Retrieving Dropdown Value in Bootstrap 5: How to Obtain the Selected Item's Value from the Dropdown Button

I am having a slight issue with my dropdown button where I am trying to display the selected item as the value of the dropdown button. The Flag Icon and Text should be changing dynamically. I have tried some examples but it seems that it is not working as ...

The API endpoint does not include the Access-Control-Allow-Origin header on its resource

I have been attempting to utilize jQuery XHR to send a basic GET request to an API on Zillow. The response is visible in my browser and Postman, displaying correct results. Although I have redacted my API key below, the request itself could not be more str ...

Struggling to integrate buttons into an h2 element with the use of createElement() and appendChild() in HTML/CSS/JS

As I work on developing a website, one of the features I've been implementing is the ability for users to add books to a list and then review or delete them. The process was smooth sailing until I reached the point of adding buttons for these actions. ...

Firefox's keyup event

Is it possible to detect a keypress using the jQuery keyup function, as I am facing an issue where it works in Chrome, Edge, IE, and Opera but not in Firefox. $(".textfield").contents().keyup(function(evnt) { document.getElementById("btn_save").style. ...

Constance in JavaScript

Looking to create constants in Javascript and seeking advice on the best way to do so. While I am aware that true constants don't technically exist, I'm finding it difficult to change values after exporting them. Are constants necessary? Is the ...

Trouble with the icon URL in AngularJS Google Map (ng-map) functionality

Whenever I switch from using a relative URL to an absolute one, my markers mysteriously disappear. In the view, I have the following code: <marker ... icon="{url: '{{markerSrc}}'}"></marker> When I set this in my controller: $scop ...

What is the best way to pass a variable within a jQuery event map?

Consider the below jQuery .on() event map: $('header').on({ mouseenter: function(e) {}, mouseleave: function(e) {}, }, 'li'); Is there a way to share a common var $this = $(this) variable between the mouseenter and mouseleave even ...

Performing a Search Operation using AJAX with Elasticsearch

I've been struggling to find the correct method for requesting data from elasticsearch using a jQuery AJAX call. I keep encountering parsing errors or getting all documents in the index instead of my intended results. $(document).ready(function() ...

Maximizing Server Performance with Query Data Caching

I am currently developing an Express app that involves transferring data from views to a database. However, the majority of the data needs to be linked to other data within different tables in the database. For instance, there is a "choose student name" d ...

What is the best method to pass a JavaScript file array to a Node.js server?

Is it possible to transfer data from a Javascript file linked to an HTML page to a Node.js file on a post route without displaying it on the HTML page? If so, what is the best way to accomplish this? ...