What is the best way to create a search function that can filter objects based on both their years and months of investment?

I recently created a website and I'm struggling with searching through multidimensional arrays or objects (I'm not sure what the difference is).

Prior to adding the year and month, I was able to access them directly by using array[id][field].

Can someone guide me on how to implement search within nested structures in a multidimensional array?

I attempted to pre-set the year and month with additional fields in the interface, but it ended up looking confusing and bizarre.

{
  "2018": {
    "Aug": {
      "1": {
        "id": 1,
        "appeal_date": "2018-08-24",
        "city_of_residence": "aaa",
        "patient_name": "John",
        "patient_age": 62,
        "coordinator": "aaa",
        "source": "aaa",
        "birth_date": "1956-06-30",
        "contact_person_name": "",
        "contact_person_role": "",
        "contact_person_phones": [
          "",
          ""
        ],
        "diagnosis": "aasasd",
        "status": "9",
        "departure_date": "2016-02-18",
        "arrival_date": "2020-01-23",
        "patient_phones": [
          "",
          ""
        ],
        "editable": true
      }
    }
  },
  "2019": {
    "Oct": {
      "65": {
        "id": 65,
        "appeal_date": "2019-10-18",
        "city_of_residence": "asfsac",
        "patient_name": "asvsas",
        "patient_age": 62,
        "coordinator": "",
        "source": "asfasfa",
        "birth_date": "1956-06-30",
        "contact_person_name": "",
        "contact_person_role": "",
        "contact_person_phones": "",
        "diagnosis": "assdbcx",
        "status": "1",
        "departure_date": "",
        "arrival_date": "",
        "patient_phones": "",
        "editable": true
      }
    },
    "Jun": {
      "64": {
        "id": 64,
        "appeal_date": "2019-06-04",
        "city_of_residence": "afsfsa",
        "patient_name": "asvac",
        "patient_age": 62,
        "coordinator": "",
        "source": "agwdawdawd",
        "birth_date": "1956-06-30",
        "contact_person_name": "",
        "contact_person_role": "",
        "contact_person_phones": "",
        "diagnosis": "agsags",
        "status": "1",
        "departure_date": "",
        "arrival_date": "",
        "patient_phones": "",
        "editable": true
      }
    }
  }
}

All I need is to update some fields within the correct object.

patients[2019]['Oct'][65]['diagnosis'] = 'aaaaa'

Something like this, but there might be instances where the patient isn't in the specific month mentioned.

I would prefer the functionality to look like this:

patients.nestingSearchByKey(65)['diagnosis'] = 'aaaaa'

The identifiers are unique and do not repeat.

Apologies for any language errors. Any suggestions are greatly appreciated.

Answer №1

To obtain an array of keys within an object, you can utilize the Object.keys method.

var elements = {
  "2021": {
    "Jan": {
      "12": {
        "id": 12,
        "name": "Alice",
        "age": 30
      }
    }
  },
  "2022": {
    "Mar": {
      "33": {
        "id": 33,
        "name": "Bob",
        "age": 25
      },
      "45": {
        "id": 45,
        "name": "Carla",
        "age": 40
      }
    }
  }
}

function findElement(obj, id) {
  var element;
  const years = Object.keys(obj);
  years.forEach(year => {
    const months = Object.keys(obj[year]);
    months.forEach(month => {
      if (obj[year][month][id]) {
        element = obj[year][month][id];
      }
    });
  });
  
  return element;
}

const e = findElement(elements, 45);
if (e) {
  e['age'] = 50;
  console.log(elements);
} else {
  console.log('Element with ID 45 not found');
}

Answer №2

Assuming that I have grasped your explanation correctly and you intend to maintain the existing object structure, all you need to do is verify if the patient exists:

var patient = patients[2019]['Oct'][65];

if (patient) {
    patient['diagnosis'] = 'aaaaa';
}

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

Utilizing an EJS template within an express.js application to extract and assign data to a variable

Is there a way to transfer data from my node.js (express) app directly to a variable within the <script> tag on the page? On the server-side, I have the following code: let tmp = JSON.stringify(await f(i)); console.log(tmp); //correct data [{"i ...

Error encountered while attempting to validate JWT

This question has been asked multiple times, but I'm still struggling to find the root cause of the issue. I have already signed some data with a token, but when I attempt to verify it, I receive an error message saying "jwt malformed". Interestingly, ...

Exploring the concept of calculating scaled distance in TopoJSON files

I have been exploring various methods to connect pixel space with real-world distances using a projection. I came across the following method which proved to be quite useful: var actual_map_bounds = d3.geo.bounds(this_topojson); var radians = d3.geo. ...

I am looking for the best way to convert a complicated JSON stored as a string into a dataframe using Spark and Scala

I am facing a challenge in creating a dataframe from a complex JSON in String format using Spark scala. My Spark version is 3.1.2 and Scala version is 2.12.14. The source data looks like this: { "info": [ { "done": "t ...

jQuery enables the creation of fresh form fields

Currently, I am working on a form that initially consists of 2 text input fields. The typical use case involves the user entering a number in one field and their name in the other. Following this, the page updates itself without reloading. However, there a ...

Having trouble with jQuery loading for the first time

I am having trouble getting the jQuery to load properly. My goal is to toggle classes on specific items identified by their ID. When an item is clicked, I want it to have the class "menu-selected" while the other item has the class "unselected." I have i ...

The information submitted through the form is not displaying on the console after being gathered using the post method in Express

When attempting to add products using a form on the admin page, the data (including an image file) is not being displayed in the console as expected. Instead, the following message appears: "{} POST /admin/add-product - - ms - -" Below is th ...

Attempted to display a Google Map within a lightbox, but encountered difficulties in getting it to

I've copied and pasted my code below. It may contain references to Google or Lightbox being undefined, but I'm unsure how to integrate them into the code provided. My goal is to display a Google map within a Lightbox popup, but so far I have been ...

interactive vuetify navigation trail elements

Currently working on a vuetify project and I'm facing an issue with implementing breadcrumbs. The problem arises when clicking on a breadcrumb, as it deletes the ones that come after it in the list. I've tried some code snippets but could only ma ...

How can I group every 3 elements in a div using React?

I've been trying to achieve a layout where there are 3 red divs enclosed within a blue div. However, despite following the suggested method from https://stackoverflow.com/questions/63695426/react-wrap-every-3-components-into-a-div, I'm unable to ...

Tips for passing dynamic latitude and longitude values to a JavaScript function within an AngularJS framework

I am facing an issue with displaying a dynamic marker on Google Maps. I can show a static lat long marker, but I am struggling to pass dynamic lat long values to the function. How can I pass {{names.lat}}, {{names.longitude}} to the function so that I can ...

I am attempting to monitor the addliquidity event on Uniswap's router02

I am currently attempting to monitor addliquidity events in order to extract data on newly added pairs const Web3 = require('web3'); const NODE_URL = "https://mainnet.infura.io/v3/d3c5832256754c85be86b4c97de2d3d3" const web3 = new We ...

I am not receiving any results from the geocoder on Google maps

I am currently working on implementing the JS geocoding api but I keep encountering an error: Failed to load resource: net::ERR_BLOCKED_BY_CLIENT Despite having my api key activated. I have tried the following: Within HTML: <script src="{% stati ...

What is the best way to retrieve the most recent value in a MongoDB aggregation?

In my collection, some documents have a status field while others do not. However, all documents contain a data field. I am trying to construct a query that retrieves the most recent values for both fields. The issue arises when using the $last operator, a ...

Operations such as OR and AND can be used within a JSONB array to filter

Imagine having a table named temp (jsondata jsonb) In Postgres, there is a method to query a jsonb array object for containment check using SELECT jsondata FROM temp WHERE (jsondata->'properties'->'home') ? 'football&apo ...

Utilizing Regular Expressions in Express.js Routes

Is there a way to extract a specific value from my URL using Express? For example, my URL structure is as follows: host/:value.schema I need to retrieve the value from this URL. Here's an example: host/horse.schema (In this case, the value wo ...

Why isn't CSS showing up in preview mode on the network tab?

I have been using nextjs for server-side rendering and I am encountering an issue where my CSS class is not being applied on the preview tab, it only works on the client side. Any idea why this is happening? Here is the code snippet: https://codesandbox.io ...

Each Vue instance on the page has its own isolated Vuex store

I have a situation where I am creating multiple Vue apps on the same page: import Vue from "vue"; import App from "./App.vue"; import useStore from "./store"; const arr = [1, 2]; for (const index of arr) { const store = use ...

The draggable=true attribute in EaselJS (MovieClip) canvas does not display a ghost image

I am currently working with a canvas element that contains animations powered by EaselJS. The canvas is wrapped in a parent div with draggable set to true. <div class="outer-parent" draggable="true"> <div class="inner-parent"> <canvas& ...

Avoid consistently updating information

I am experiencing a strange issue in my project. I have 2 tabs, and in one tab, there are checkboxes and a submit button. The user selects items from the checkboxes, and upon clicking the button, they should see their selections in the other tab. This fu ...