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.