Looking to retrieve object values in JavaScript in a dynamic manner?

Imagine having an array of objects with nested objects. The data is always changing, meaning the keys may vary each time. For instance:

[
{
    "uuid": "53e7202c-28c8-4083-b910-a92c946a7626",
    "extraIdentifiers": {
      "National ID": "NAT2804"
    },
    "givenName": "Krishnan",
    "customAttribute": null,
    "age": "32"
},
{
    "uuid": "9717ec58-8f87-4305-a57b-bed54301def7",
    "extraIdentifiers": {
      "National ID": "NAT2805"
    },
    "givenName": "Dale",
    "customAttribute": null,
    "age": "32"
},
{
    "uuid": "d3563522-927d-4ff0-b697-eb164289a77d",
    "extraIdentifiers": {
      "National ID": "NAT2806"
    },
    "givenName": "David",
    "age": "32"
}
]

Now, there's a function that retrieves values from one of the keys. For example, if we want to get the givenName, it will return David.

Here's the code snippet for this:

$scope.sortPatient = function (param) {
    $scope.results.map(function (currentObj) {
        console.log(currentObj[param]);
    })
};

The $scope.results contains the JSON objects above. When calling sortPatient, we would provide the specific key whose value we need. For instance: sortPatient('givenName') or sortPatient('age').

If we try

sortPatient('extraIdentifiers.National ID')
, instead of logging NAT2804, it shows undefined in the console. Attempting
sortPatient('extraIdentifiers[National ID]')
yields the same result.

How can we access the values of keys within nested objects? The function call cannot be modified; only its definition. Currently, obtaining values from complex objects remains a challenge.

Answer №1

To improve your method, consider passing an array of keys and then checking if the object contains the specified key path.

$scope.sortPatient = function (keys) {
  $scope.results.map(function (currentObj) {
     var result = currentObj;
     keys.forEach(function(key){
        if(result[key]) result = result[key];
     })
     console.log("result", result);
  })
};

$scope.sortPatient(['extraIdentifiers','National 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

Extracting the input data from a JSON source

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Testing AJAX Requests ...

"Why does Sequelize migration successfully create a table, yet the models are unable to establish a connection to the

I am currently learning how to use the Sequelize ORM in Node.js and save data in a PostgreSQL database. My primary objective is to insert user data into the Users table. I have successfully created the table using migration; however, I am encountering dif ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

Sequence of HTML elements arranged in a stack

Recently, I came across a useful jQuery tutorial called "jQuery for Absolute Beginners: Day 8". In this tutorial, there is an interesting code snippet that caught my attention: $(function() { $('.wrap').hover(function() { $(this).childre ...

Preventing long int types from being stored as strings in IndexedDB

The behavior of IndexedDB is causing some unexpected results. When attempting to store a long integer number, it is being stored as a string. This can cause issues with indexing and sorting the data. For instance: const data: { id: string, dateCreated ...

Exploring a multitude of data within a hefty json log document using node.js

I am dealing with a JSON file named sensorlogs.json that contains data from different sensors transmitting at varying frequencies. The timestamps in the file are not in order and one sensor may have missing entries. The goal is to analyze each sensor&apos ...

Retrieving the response value in AngularJS with $resource

I'm trying to retrieve the response of a request using $resource in AngularJS. Here is an example implementation: angular.module('app').factory('AuthResource', ['$resource', function($resource) { return { isA ...

Unable to load circles on page refresh with amCharts Maps

I am experiencing an issue with the functionality of my amCharts maps. Whenever I refresh the page, the circles that are supposed to be displayed disappear. However, when I zoom in, the circles reappear. This problem has me puzzled, and I'm not sure ...

Troubleshooting problem with decrypting data using CryptoJS AES256

I am currently facing an issue with the decryption of a URL that has been encoded using AES256. I am using CryptoJS for the decryption process, but I keep encountering the following exception: Malformed UTF-8 data Have I missed something in the code? rout ...

Understanding how to parse a JSON array with various key-value pairs is crucial for

I have a project where I need to parse a JSON array with varying key names, such as: { "details": [ { "state": "myState1", "place": [ { "name": "placeName" } ] }, { "state": "myState2", "place": [ { "name1": "placeName ...

Why does a Vue component throw errors prior to being rendered?

In the Home view, there are two components: Filter and Results. The Results component relies heavily on data from the vuex store, which is influenced by the Filter component. Once the filters are applied and the user interacts with Filter, the necessary da ...

Issues with routing in AngularJS 1.0 are causing difficulties

Trying out an AngularJS 1.0 application and running into routing issues. Routes are not functioning properly, templates aren't displaying within ng-view. See my code below. package.json "main": "server.js", "dependencies": { "angular": " ...

Is there a way to organize items in an array alphabetically according to a predetermined key value?

I have an array of objects containing countries with various values for each country. My goal is to list them alphabetically. // globalBrands { [ { id: 1, title: 'Argentina', content: [{url: 'w ...

What exactly does the term "entry point" refer to within the context of npm init?

Starting a new project can be overwhelming, especially when faced with a list of questions during the npm init process. One question that often stumps developers is "entry point." The options provided, like name, version, and description, may seem straig ...

JavaScript that is subtle and lacks function parameters

Suppose you have: <div id="data" onclick="handleData(1)">Datum 1</div> and you prefer late binding instead: <div id="data">Datum 1</div> <script> $("#data").click(function() { handleData(1); }) </script&g ...

`show a div only when at least one checkbox is selected using AngularJS`

As a beginner in angularjs, I am looking to display a div with delete, rename, and move buttons when an image in a gallery (which contains a checkbox) is clicked. There are many images present, so I want the div to be visible only when at least one check ...

Retrieve the text content from the HTML document

I'm facing a beginner's challenge. I have a div element and I want to extract the URL from the data-element attribute into a .json file Is there a way to do this? <div content="" id="preview" data-element="http://thereislink" class="sample ...

Access the id of an object in an array using Vue.js

Is there a way to showcase value data depending on the index array? I have created a modal for editing data, with a JSON structure like this: [ { "ID": 3, "idusers": 3, "skills": "Go", ...

Reserve a spot for a credit card in 4-digit format with VueJS

When I enter a credit card number, I want to automatically insert a space after every 4 digits. For example: 0000 0000 0000 0000 I am currently using vue js and have come across examples using jquery, but I prefer not to use jquery. Any help would be appr ...

Ways to verify the presence of isBrowser in Angular 4

Previously, isBrowser from Angular Universal could be used to determine if your page was being rendered in a browser (allowing for usage of features like localStorage) or if it was being pre-rendered on the server side. However, it appears that angular2-u ...