从数组中使用键获取值- Angularjs [duplicate]

hmmo2u0o  于 11个月前  发布在  Angular
关注(0)|答案(4)|浏览(129)

此问题在此处已有答案

Find object by id in an array of JavaScript objects(37个答案)
7年前关闭。
我想从一个数组中的key中得到一个特定的值

$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":"[email protected]"
    }
    ];

字符串
如何获取“logo_big”的值?

$scope.result['logo_big']


返回undefined

xtfmy6hx

xtfmy6hx1#

const obj = $scope.results.filter(e => e.key == "logo_big")[0];

字符串
参见MDN Documentation

bd1hkmkf

bd1hkmkf2#

你需要循环遍历数组来找到具有给定键的元素。
或者,如果您的系统支持Array.find():

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

字符串
一个不太理想的解决方案是使用过滤器:

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

h5qlskok

h5qlskok3#

你首先有一个数组,每个数组项都是一个对象,所以如果你想访问它,你必须遵循下面的步骤

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

字符串

p5cysglq

p5cysglq4#

如果你想以Angular 的方式做,使用angular.foreach并检查对象的键

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

字符串

演示

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": "[email protected]"
  }];

  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>

的数据

相关问题