1

How to get key of a json which resides within a array based on value, say if the value as ValueB it should return 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"));

});

Can anyone please tell me some solution for this

1
  • Can you share the code you have written so far? Commented Nov 19, 2014 at 15:06

3 Answers 3

2

Here is a small function that should do what you want, as long as the values are unique:

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

Sign up to request clarification or add additional context in comments.

1 Comment

@AlexMan should be the same, just send $scope.myDatas instead of arr
1

You haven't shared too much code here, so I'm not sure what the best solution would be. However, to simply answer you question, you could use this example: Convert JSON to a js object via $.parseJSON(), and then find your key:

function getKeyInArray(arr, val){
    for(var i=0, len=arr.length;i<len;i++){
        var obj = arr[i];
        for(var key in obj){
            if(obj[key] == val)
                return key;      
        }
    }
    return null;
}

view example: http://jsfiddle.net/wc3mhg8u/21/

1 Comment

Haha, seems like juvian beat me to it.
1

Try this

$scope.getJsonKey = function(jsonArray, jsonValue) 
    {
        angular.forEach(jsonArray, function(value, index) 
        {
           for(var key in value) {

            if (value === jsonValue) 
            {
                return key
            }

            }
        });
    };
       console.log($scope.getJsonKey($scope.myDatas, "ValueB"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.