Tips on Calculating the Number of Object Properties and Presenting Each Value Individually on a Dynamic Button with Click Event Attached

When it comes to displaying dynamic data with markers on a map, everything works fine up until this point. However, I've encountered some issues that I'm currently stuck on and not sure how to proceed.

Dynamic data:

{
    "page": 2,

    "data": [
        {
            "id": 4,
            "first_name": "Eve",
            "last_name": "Holt",
            "lat":"25.6599899",
            "lng":"45.3664646",
            "status":"0"

        },
        {
            "id": 5,
            "first_name": "Charles",
            "last_name": "Morris",
            "lat":"25.99899",
            "lng":"45.4646",
             "status":"1"

        },
        {
            "id": 6,
            "first_name": "Tracey",
            "last_name": "Ramos",
            "lat":"25.2339899",
            "lng":"45.56664646",
            "status":"1"

        }
    ]
}

Issue 1: Count the occurrences of 'Status' value being 0 and 1

Issue 2: After counting, if there are 3 people with Status 1, display individual buttons dynamically for each person; likewise for Status 0

Issue 3: Clicking on a specific button should trigger an info window to open on the map at the corresponding marker location

This is my Dynamic Marker Code:

 addMarker(latlng, mapobj, markerLabel, iconColor) {

          this.iconDisplay =[];

         if(iconColor === "0"){
            this.iconDisplay = this.red;

         }else if(iconColor === "1"){
             this.iconDisplay = this.green;

         }else if(iconColor === "2"){
             this.iconDisplay = this.orange;

         }else if(iconColor === "3"){
          this.iconDisplay = this.building;
      };
      
      // Additional marker code here...

Answer №1

To achieve this functionality, you can refer to the code snippet provided below:

const inputData = {
    "page": 3,
    "data": [{
        "id": 1,
        "first_name": "Niraj",
        "last_name": "Paudel",
        "lat": "454.454",
        "lng": "454545",
        "status": "0"
    },
    {
        "id": 2,
        "first_name": "Kushal",
        "last_name": "Shrestha",
        "lat": "235.99899",
        "lng": "452.4646",
        "status": "1"
    },
    {
        "id": 3,
        "first_name": "Ritesh",
        "last_name": "Sainju",
        "lat": "253.3439899",
        "lng": "423.56664646",
        "status": "1"

    }
    ]
}

let statusZeroObjects  = inputData.data.filter(item => item.status === 0);
let statusOneObjects = inputData.data.filter(item => item.status === 1);

//To address Issue 1
const countOfStatus0 = statusZeroObjects.length;
const countOfStatus1 = statusOneObjects.length;

//To address Issue 2
//Add buttons for status zero in container0 div
statusZeroObjects.forEach(function(person) {
    addCustomButton('#container0', person);
});

//Add buttons for status one in container1 div
statusOneObjects.forEach(function(person){
    addCustomButton('#container1', person);
});

function addCustomButton(id, individual) {
    let button = document.createElement("input");
    button.type = button;
    button.name =  individual.first_name;
    button.onClick = addMapMarker(individual); //Functionality related to marker is not clear
    document.getElementById(id).appendChild(button);
}


// To handle Issue 3
const addMapMarker = function(individual) {
// Implement logic for map markers here
}

Answer №2

To tally the number of zeros and ones in an array, you can use the .reduce method:

const input = {
  "page": 2,
  "data": [{
      "id": 5,
      "first_name": "Alice",
      "last_name": "Smith",
      "lat": "25.6599899",
      "lng": "45.3664646",
      "status": "0"
    },
    {
      "id": 6,
      "first_name": "Bob",
      "last_name": "Johnson",
      "lat": "25.99899",
      "lng": "45.4646",
      "status": "1"
    },
    {
      "id": 7,
      "first_name": "Eve",
      "last_name": "Williams",
      "lat": "25.2339899",
      "lng": "45.56664646",
      "status": "1"

    }
  ]
}
const { zeroCount, oneCount } = input.data.reduce( ({ zeroCount = 0, oneCount = 0 } = {}, { status }) => {
  if (status === '0') zeroCount++;
  if (status === '1') oneCount++;
  return { zeroCount, oneCount }
}, {});
console.log('Total Zeros: ' + zeroCount + ', Total Ones: ' + oneCount);

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

Having trouble getting SVG animations to work properly when using the static folder in Parcel?

As I was attempting to display my SVG file on the browser after uploading it to my domain, I followed a similar process to other projects where I had installed parcel. This involved creating a static folder and placing the SVG file inside it. While the SVG ...

Is there a way to automatically update the button text based on the route name without requiring user interaction?

I need to dynamically change the text on a button in my header based on the current route. When on the login page, the button should say "Signup" and when on the signup page, it should say "Login". I want this text change to happen without having to click ...

I consistently encounter the error message 'XRWebGLLayer is not defined no-undef' while implementing three.js within react.js to develop a WebXR application

Trying to implement WebXR with Three.js in a React project, encountering the error: 'XRWebGLLayer' is not defined no-undef for baseLayer: new XRWebGLLayer(session, gl) The code works fine in vanilla JavaScript but fails to compile in React. ...

Guide to correctly passing custom parameters along with the event object to an asynchronous form submission handler

Asking for guidance on defining and typing custom parameters alongside the native event object in an async onSubmitHandler for a form. The current implementation only receives the native event as a single parameter: const onSubmitHandler: FormEventHa ...

What is the best way to retrieve recently inserted data using Sequelize in PostgreSql?

Is there a way to retrieve updated table values after adding a user to the "WOD" table without making an additional query? Currently, when I add a third user to my WOD table, I can only return the first two users because I am unable to access the updated ...

Change the background color of a span element dynamically

I am currently working on implementing dynamic background coloring for a span tag in my Angular view that displays document types. The code snippet provided is as follows: <mat-card *ngFor="let record of records"> <span class="doc ...

Attempting to send an AJAX request to a different server (not functioning with the provided example)

UPDATE - Issue Resolved. Many thanks to everyone who provided input. After conducting extensive research, I discovered that instead of CORS, I needed to focus on JSONP all along. I have read several tutorials and believe I now have a good grasp of the con ...

jQuery is unable to manipulate newly added DOM elements that have been loaded via AJAX

Having trouble with jquery ajax. Unable to interact with newly added element through ajax. Code snippet: $(".yorum_input").keypress(function(e) { if (e.keyCode == 13) { e.preventDefault(); var alt_id = $(this).attr('yorum_id'); va ...

What is the best way to create a generic array and combine properties?

I have a scenario where I have two objects defined as one and two, each containing props. These objects are then stored in an array called packages. const one = { props: { num: 2 } } const two ={ props: { nam ...

An efficient method for removing a column using JavaScript

Hello, I'm seeking assistance with the following code snippet: $(document).on('click', 'button[id=delete_column]', function () { if (col_number > 1) { $('#column' + col_number).remove(); $('#col ...

What steps should I take to address this 'key' alert?

My browser console is displaying the following error message: Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information. ExpenseList@http://localhost:3000/main.cfec1fef7369377b9a ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Including additional data to a page after each iteration in order to display the current progress

I am currently working on a loop that iterates through the lines of a text area and processes each line sequentially. However, I am facing an issue where the page becomes unresponsive until all the data has been processed. Is there a way to dynamically u ...

The absence of a closing parentheses in the argument is causing an issue when rendering

Apologies for the basic mistake, but I could really use some assistance with this syntax error. I've spent over an hour searching for it and still haven't been able to locate the issue. It seems to be around the success function(data) section. Th ...

Displaying and concealing a div based on the scroll position

I have implemented a script that hides a div and then shows it when I scroll past a certain point on the page. It is working correctly, but once I scroll back up to the top, the div remains visible. Can someone suggest a modification to the code that will ...

Unable to determine all parameters for Modal: (?, ?, ?)

import { Component, Inject } from '@angular/core'; import { NavController, Modal } from 'ionic-angular'; import { PopupPage } from '../../components/modal/modal.page'; @Component({ templateUrl: 'build/pages/spot/spot. ...

Adding text chips to a text field in Vuetify - A simple guide

I have successfully integrated a text field with vuetify and now I am looking to incorporate chips into it. Currently, chips are only added if the entered text matches a specific pattern (such as starting with '{' and ending with '}'). ...

Experimenting with viewProvider in a component test

@Component({ selector: 'app-entity-details', templateUrl: './entity-details.component.html', styleUrls: ['./entity-details.component.scss'], viewProviders: [{ provide: ControlContainer, useFactory: (container: ...

Angular's interactive checkboxes and dropdown menus provide a dynamic user experience

There is a global List array where data from an API is passed in the OnInit method. List: any; visibility:any; Status:any; ngOnInit(): void { let param = {...}; this.Service.getUser(param).subscribe(result => { this.List = result['response ...

Failed to install @ngrx/store due to unforeseen issues

Having issues with the installation of @ngrx/store My current setup includes: Node 8.9.3, NPM 5.5.1, Angular CLI 1.7.4, Angular 5.2.0 I am using Angular CLI to create a new Angular application and attempting to add @ngrx/store by running the following c ...