如何基于值获取驻留在数组中的json的键,说如果该值作为ValueB,则应返回MainB

var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
   $scope.myDatas =  [
      {
        "Test1": "Value1",
        "MainA": ""
      },
      {
        "Test1": "Value2",
        "MainA": "ValueB"
      },
      {
        "Test1": "",
        "MainA": "ValueC"
      }
    ];

    $scope.getJsonKey = function(jsonArray, jsonValue)
    {
        angular.forEach(jsonArray, function(value, index)
        {
            if (value.Test1 === jsonValue)
            {
                return "Test1";
            }
            if (value.MainA === jsonValue)
            {
                return "MainA";
            }
        });
    };
   console.log($scope.getJsonKey($scope.myDatas, "ValueB"));

});


谁能告诉我一些解决方案

最佳答案

只要值是唯一的,这是一个应该执行所需操作的小函数:



var arr=[
      {
        "Test1": "Value1",
        "MainA": "ValueA"
      },
      {
        "Test2": "Value2",
        "MainB": "ValueB"
      },
      {
        "Test3": "Value3",
        "MainC": "ValueC"
      }
    ]


function getKey(arr, val){
    for(var i=0;i<arr.length;i++){
        var item= arr[i];
        for(var key in item){
            if(val === item[key]) return key;
        }
    }
    return null; // not found
}

console.log(getKey(arr, 'ValueB')) // MainB

08-15 14:34