1

I want get a specific value from key inside an array like that

   $scope.result = [
{

    "key":"logo_big",
    "value":"/assets/images/aaa.jpg"
    },
    {
    "key":"logo_small",
    "value":"/assets/images/logo94x57Bis.png"
    },
    {
    "key":"project_name",
    "value":"Company"
    },
    {
    "key":"support_email",
    "value":"dev@gmail.com"
    }
    ];

How can I get a value of 'logo_big'?

$scope.result['logo_big'] 

return undefined

Cœur
  • 37,241
  • 25
  • 195
  • 267
Silvio Troia
  • 1,439
  • 19
  • 36
  • Personally, I'd recommend using a library such as [lodash](https://lodash.com), which as an awesome [find](https://lodash.com/docs/4.17.2#find) function, which could be used in your example as `var item = _.find($scope.result, {key: 'logo_big'});` – random_user_name Dec 07 '16 at 18:04

4 Answers4

1

You need to loop through the array to find the element which has the given key.

Or, if Array.find() is supported on your system:

var item = $scope.result.find(function(element) {
    return element.key === 'logo_big';
});
return item && item.value;

A less optimal solution is to use filter:

var item = $scope.result.filter(function(element) {
    return element.key === 'logo_big';
})[0];
return item && item.value;
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1
const obj = $scope.results.filter(e => e.key == "logo_big")[0];

See the MDN Documentation

nicovank
  • 3,157
  • 1
  • 21
  • 42
0

You have an array first and each array item is a object so if you want to access you have to follow below

for (var i = 0 ; i < $scope.result.length; i++) 
{
  if ($scope.result[i]["key"] == "logo_big") 
  {
   alert("found value");
  } 
}
0

If you want to do in angular way, use angular.foreach and check for object's key

angular.forEach($scope.result, function(obj) {
      if (obj.key == "logo_big") {
        $scope.resultObj = obj.value;
        alert($scope.resultObj);
      }

DEMO

var app = angular.module("app", []);
app.controller("listController", ["$scope", function($scope) {
  $scope.name = 'StackOverflow';
  $scope.result = [{
    "key": "logo_big",
    "value": "/assets/images/aaa.jpg"
  }, {
    "key": "logo_small",
    "value": "/assets/images/logo94x57Bis.png"
  }, {
    "key": "project_name",
    "value": "Company"
  }, {
    "key": "support_email",
    "value": "dev@gmail.com"
  }];

  angular.forEach($scope.result, function(obj) {
    if (obj.key == "logo_big") {
      $scope.resultObj = obj.value;
    }
  });

}]);
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://code.angularjs.org/1.4.7/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="listController">
  <h3>Enter an ID</h3>
   <h1> {{resultObj}}</h1>
</body>

</html>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396