【问题标题】:How do I dynamically get the values from Objects in Javascript? [duplicate]如何从Javascript中的对象动态获取值? [复制]
【发布时间】:2020-04-11 18:57:33
【问题描述】:

假设我有一个对象数组,其中的对象包含对象。该数据是动态的,即键不会相同,可能会有所不同。 例如:

[
{
    "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"
}
]

现在我有一个函数可以从其中一个键中获取值。例如,我想得到givenName,所以它会返回David

这是它的代码:

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

$scope.results 将保存上述 JSON 对象。在调用 sortPatient 时,我会通过传递我想要的值的key 来调用它。例如:sortPatient('givenName')sortPatient('age')

这将在控制台中记录Dale32。但是,如果我调用sortPatient('extraIdentifiers.National ID'),它不会在控制台中记录NAT2804,而是记录未定义。我也试过像sortPatient('extraIdentifiers[National ID]') 这样称呼它,但它仍然显示未定义。

如何获取键中键的值?我也无法更改调用函数的方式。我只能更改它的定义。但我无法获取复杂对象中键的值。

【问题讨论】:

  • 这就是我需要的。但我无法理解解决方案的工作原理。你能帮我理解吗?谢谢

标签: javascript arrays json angularjs


【解决方案1】:

我会改为将带有键的数组传递给您的方法,然后检查对象是否包含给定的键路径。

$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']);

【讨论】:

  • 酷,也想写这样的东西。而不必传递数组,他也可以使用String.split('.') 解析函数内部的param - 所以extraIdentifiers.NationalID 将变为['extraIdentifiers','National ID']
  • @Gibor 是的。这也可以,而且是一个不错的选择。
猜你喜欢
  • 2019-08-07
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2010-12-27
  • 2023-03-12
相关资源
最近更新 更多