使用angularjs和Javascript将对象数组数据中的一个字段转换为另一个值
在angularjs控制器中,我有以下代码:使用angularjs和Javascript将对象数组数据中的一个字段转换为另一个值,javascript,arrays,angularjs,Javascript,Arrays,Angularjs,在angularjs控制器中,我有以下代码: var ysshControllers = angular.module('theControllers', []); ysshControllers.controller('CommonController', function($scope, $http, $route) { $scope.dbKey = $route.current.customInput; $scope.urlToDb = 'http
var ysshControllers = angular.module('theControllers', []);
ysshControllers.controller('CommonController',
function($scope, $http, $route) {
$scope.dbKey = $route.current.customInput;
$scope.urlToDb = 'https://' + $scope.dbKey + '/.json';
$http.get($scope.urlToDb).success(function(data) {
var values = [];
for (var name in data) {
values.push(data[name]);
}
$scope.Items = values;
});
// Initially order by date and time
$scope.orderProp = 'ac';
}
);
它创建一个名为Items
的对象数组。键值只是标上了aa
,ab
,ac
等。当用户从下拉菜单输入数据时,我只想保存如下值:1,2,3,4,5
,然后当数据导入网站时,将值转换回来。像0
=坏的<代码>5
=非常好
。因此,对于每个键名为ae
的记录,我想将值从1,2,3,4,5转换为Bad,ok,Fair,Good,Very Good
我可以理解程序流程,我需要知道的是如何使用面向对象的JavaScript引用值
数据的结构如下所示:
C5_200630_Option 1
aa:"Option 1"
ab:"Toyota"
ac:6499
ad:"Truck"
ae:"Tacoma, Silver, 1/2 ton 4wd"
af:4
我运行了类似这样的代码:
alert(Object.keys($scope.UsedItems));
它给出了0,1,2,3,4
等的值。所以我猜$scope.UsedItems
中的键值只是数字。我不知道如何访问密钥和值数据。在警报中显示数组内容的简单方法是什么
我用了这句话:
alert(data[name].ad);
这将引用每个记录中名为ad
的数据。因此,这给了我一种识别记录中特定项目的方法
好吧,我想出了一个解决办法:
if (data[name].af === "3") {
data[name].af = "Awesome!";
}
即使我找到了解决问题的办法,我仍然几乎不知道自己在做什么。如果有更好的方法,请告诉我。您可以这样定义一个数组
var example = ["Bad", "Not Bad", "Fine", "Good", "Very Good"];
data[name].af = example[data[name].af];
而不是每次都检查data[name].af的值,您可以这样简单地设置它
var example = ["Bad", "Not Bad", "Fine", "Good", "Very Good"];
data[name].af = example[data[name].af];
这将为您提供所需的结果,因为您需要数据[name]。af=3应该可以,示例[3]就是您想要的