Javascript 在数组Angular JS中转换对象的简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30392626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is easy way to convert object in array Angular JS?
提问by vaved
My application was built on Angular JS and has a lot AJAX requests on server. For example, in PHP I format output arraylike as:
我的应用程序是基于 Angular JS 构建的,并且在服务器上有很多 AJAX 请求。例如,在 PHP 中,我将输出数组格式化为:
$dialog[$userId] = array(
'time' => $key,
'message' => $message['message'],
'name_user' => $info['name']
);
echo json_encode($dialog); die();
But in Angular JS I get not array but object:
但是在 Angular JS 中,我得到的不是数组而是对象:
549: Objectid_user: "549"message: "Hello"name_user: "Ali Akhmedov"time: 1432070505
549:Objectid_user:“549”消息:“你好”name_user:“Ali Akhmedov”时间:1432070505
Problem that if use ng-repeatthen does not work sorting for object.
Why in PHP I set array but on client get object?
问题是,如果使用ng-repeat则无法对对象进行排序。为什么在 PHP 中我设置数组但在客户端获取对象?
What easy way to convert object to array? Because I have a lot objects on page from AJAX.
将对象转换为数组的简单方法是什么?因为我在 AJAX 页面上有很多对象。
回答by Vadim
You don't need to convert object to array in order to iterate over it in ng-repeat. You can just use the following syntax:
您无需将对象转换为数组即可在ng-repeat. 您可以只使用以下语法:
<div ng-repeat="(key, value) in items">{{key}} => {{value}}</div>
Documentationof ngRepeat.
文档的ngRepeat。
Unfortunately, this approach will not work with orderByfilter. To iterate over object properties in specific order, you need to implement your own filter. It may be something like that:
不幸的是,这种方法不适用于orderBy过滤器。要以特定顺序迭代对象属性,您需要实现自己的过滤器。它可能是这样的:
JavaScript
JavaScript
angular.module('app', []).
filter('orderByKey', ['$filter', function($filter) {
return function(items, field, reverse) {
var keys = $filter('orderBy')(Object.keys(items), field, reverse),
obj = {};
keys.forEach(function(key) {
obj[key] = items[key];
});
return obj;
};
}]);
HTML
HTML
<div ng-repeat="(key, value) in items | orderByKey:'-'">{{key}} => {{value}}</div>
Plunker
普朗克
http://plnkr.co/edit/DJo0Y6GaOzSuoi202Hkj?p=preview
http://plnkr.co/edit/DJo0Y6GaOzSuoi202Hkj?p=preview
However even this approach will work only starting from 1.4.x, since as it is stated in documentation, AngularJS prior to 1.4.xwill sort object properties in alphabetic order while iterating over them in ngRepeat.
然而,即使这种方法也只能从 开始工作1.4.x,因为正如文档中所述,AngularJS before1.4.x将按字母顺序对对象属性进行排序,同时在ngRepeat.
In order to make it work in Angular 1.3.xor even 1.2.xyou may perform conversion of object to array of objects, each one of which will contain keyand valueproperties. That way you will be able to use it in ngRepeatin combination with filters including orderBy. Here is a code:
为了使其在 Angular 中工作,1.3.x甚至1.2.x您可以执行对象到对象数组的转换,每个对象都将包含key和value属性。这样您就可以将它ngRepeat与包括orderBy. 这是一个代码:
JavaScript
JavaScript
angular.module('app', []).
factory('srv', ['$http', function($http) {
var items = [],
loaded = false;
return {
getItems: function() {
if(!loaded) { // Lazy loading
$http.get('data.json').success(function(data) { // {key1: 'val1', key2: 'val2'}
Object.keys(data).forEach(function(key) {
items.push({key: key, value: data[key]});
});
});
loaded = true;
}
return items; // [{key: 'key1', value:'val1'}, {key:'key2', value: 'val2'}]
}
};
}]).
controller('ctrl', ['$scope', 'srv', function($scope, srv) {
$scope.items = srv.getItems();
}]);
HTML
HTML
<div ng-repeat="item in items | orderBy:'-key'">{{item.key}} => {{item.value}}</div>
Plunker
普朗克
回答by Razvan B.
Let's say you have an object like:
假设您有一个对象,例如:
$scope.myObj = {type:"Fiat", model:500, color:"white"};
Then, in your angular Controlleryou can do something like:
然后,在您的角度中,Controller您可以执行以下操作:
$scope.array = [];
angular.forEach($scope.myObj, function(element) {
$scope.array.push(element);
});
and then in your HTML
然后在你的 HTML
<div ng-repeat="obj in array">{{obj}}</div>
Here is a demo plunker
这是一个演示plunker
回答by Javarome
orderByis a filter, and filters require an array. So a straightforward solution is to combine it with a toArrayfilter. Supposing you want to order your objects using their timeproperty:
orderBy是一个过滤器,过滤器需要一个数组。因此,一个简单的解决方案是将其与toArray过滤器结合使用。假设您想使用对象的time属性对对象进行排序:
<ol>
<li ng-repeat="value in objectWithValues | toArray | orderBy: 'time'">
{{value.name_user}} said <q>{{value.message}}</q> on {{value.time|date}}
</li>
</ol>
As the toArrayfilter is not shipped with AngularJS, you can define one as:
由于toArray过滤器未随 AngularJS 一起提供,您可以将其定义为:
angular.module('ToArrayDemo', [])
.filter('toArray', function() {
return function(obj) {
const result = [];
angular.forEach(obj, function(val) {
result.push(val);
});
return result;
}
});

