我想从数组中的键中获取特定值
$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"
}
];
如何获得'logo_big'的值?
$scope.result['logo_big']
返回undefined
答案 0 :(得分:1)
您需要遍历数组以查找具有给定键的元素。
或者,如果您的系统支持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;
答案 1 :(得分:1)
const obj = $scope.results.filter(e => e.key == "logo_big")[0];
答案 2 :(得分:0)
您首先拥有一个数组,每个数组项都是一个对象,因此如果您想访问,则必须遵循以下内容
for (var i = 0 ; i < $scope.result.length; i++)
{
if ($scope.result[i]["key"] == "logo_big")
{
alert("found value");
}
}
答案 3 :(得分:0)
如果你想以角度方式做,请使用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": "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>