0

So say that I have an array of objects with objects within the objects. This data is dynamic, i.e the keys wont be the same , it may differ. For example:

[
{
    "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 I have a function which will get the value from one of the keys. For eg , I want to get the givenName so it will return David for example.

This is the code for it:

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

The $scope.results will hold the above JSON Obj. When calling sortPatient I would call it by passing the key whose value I want. For eg: sortPatient('givenName') or sortPatient('age').

This would log Dale or 32 in the console. But if I call sortPatient('extraIdentifiers.National ID') it does not log NAT2804 in the console, but logs undefined. I also tried calling it like sortPatient('extraIdentifiers[National ID]') but it still shows undefined.

How would I be able to get the values of keys inside keys? I also cannot change the way the function is being called. I can only change its definition., but I'm not able to get the values of keys inside complex objects.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
krishnanspace
  • 403
  • 1
  • 7
  • 17
  • That is what I need. But I'm not able to understand how the solution works. Could you please help me understand it? Thanks – krishnanspace Dec 19 '19 at 08:00

1 Answers1

1

I would pass an array with keys to your method instead, and then check if the object contains the given key path.

$scope.sortPatient = function (params) {
  $scope.results.map(function (currentObj) {
     var res = currentObj;
     params.forEach(function(param){
        if(res[param]) res = res[param];
     })
     console.log("res",res);
  })
};

$scope.sortPatient(['extraIdentifiers','National ID']);
John
  • 10,165
  • 5
  • 55
  • 71
  • cool, wanted to write something like this as well. instead of having to pass array he could also just parse the `param` inside the function using `String.split('.')` - so `extraIdentifiers.NationalID` would become `['extraIdentifiers','National ID']`. – Gibor Dec 19 '19 at 07:56
  • @Gibor Yes. That would work as well, and is a nice alternative. – John Dec 19 '19 at 08:00