在数组Angular JS中转换对象的简单方法是什么? [英] What is easy way to convert object in array Angular JS?

查看:99
本文介绍了在数组Angular JS中转换对象的简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序是基于Angular JS构建的,并且在服务器上有很多AJAX请求。
例如,在PHP中,我将输出数组格式化为:

  $ dialog [ $ userId] =数组(
'时间'=> $ key,
'消息'=> $ message ['消息'],
'name_user'=> $ info [ 'name']
);

echo json_encode($ dialog);死();

但是在Angular JS中,我得到的不是数组而是对象:


549:Objectid_user:549消息:你好name_user:Ali
Akhmedov时间:1432070505


如果使用 ng-repeat ,则无法对对象进行排序。
为什么在PHP中我设置数组但是在客户端获取对象?



将对象转换为数组的简单方法是什么?因为我在AJAX页面上有很多对象。

解决方案

你不需要将对象转换为数组以便迭代在 ng-repeat 中。您可以使用以下语法:

 < div ng-repeat =(键,值)项目> {{key}} => {{值}}< / DIV> 

ngRepeat 的api / ng / directive / ngRepeat>文档



不幸的是,这种方法将会无法使用 orderBy 过滤器。要按特定顺序迭代对象属性,您需要实现自己的过滤器。它可能是这样的:



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];
});
返回obj;
};
}]);

HTML



<商品中的pre> < div ng-repeat =(键,值)| orderByKey:' - '> {{key}} => {{值}}< / DIV>

Plunker



http://plnkr.co/edit/DJo0Y6GaOzSuoi202Hkj?p=preview



然而,即使这种方法只能从 1.4.x 开始,因为正如文档中所述,AngularJS在 1.4.x 将按字母顺序对对象属性进行排序,同时在 ngRepeat 中迭代它们。



为了使其在Angular 1.3.x 或甚至 1.2.x 中工作,您可以执行转换对象数组,每个对象将包含属性。这样你就可以在 ngRepeat 中结合使用过滤器,包括 orderBy 。以下是代码:



JavaScript

  angular.module('app',[])。 
factory('srv',['$ http',函数($ http){
var items = [],
loaded = false;
return {
getItems:function(){
if(!loaded){//延迟加载
$ 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;
}
返回项目; // [{key:'key1',value:'val1'},{ key:'key2',value:'val2'}]
}
};
}])。
controller('ctrl',['$ scope','srv',function($ scope,srv){
$ scope.items = srv.getItems();
}]) ;

HTML

 < div ng-repeat =项目中的项目| orderBy:' -  key'> {{item.key}} => {{item.value}}< / DIV> 

Plunker



http://plnkr.co/edit/UXmlm1GKYRZzrOV5pMYT?p=preview


My application was built on Angular JS and has a lot AJAX requests on server. For example, in PHP I format output array like as:

$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:

549: Objectid_user: "549"message: "Hello"name_user: "Ali Akhmedov"time: 1432070505

Problem that if use ng-repeat then does not work sorting for object. Why in PHP I set array but on client get object?

What easy way to convert object to array? Because I have a lot objects on page from AJAX.

解决方案

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:

<div ng-repeat="(key, value) in items">{{key}} => {{value}}</div>

Documentation of ngRepeat.

Unfortunately, this approach will not work with orderBy filter. To iterate over object properties in specific order, you need to implement your own filter. It may be something like that:

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

<div ng-repeat="(key, value) in items | orderByKey:'-'">{{key}} => {{value}}</div>

Plunker

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.x will sort object properties in alphabetic order while iterating over them in ngRepeat.

In order to make it work in Angular 1.3.x or even 1.2.x you may perform conversion of object to array of objects, each one of which will contain key and value properties. That way you will be able to use it in ngRepeat in combination with filters including orderBy. Here is a code:

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

<div ng-repeat="item in items | orderBy:'-key'">{{item.key}} => {{item.value}}</div>

Plunker

http://plnkr.co/edit/UXmlm1GKYRZzrOV5pMYT?p=preview

这篇关于在数组Angular JS中转换对象的简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆