Convert Object to Array Angularjs

时间:2017-04-06 16:52:34

标签: angularjs arrays google-visualization

I'm working with google charts using angularJs. The problem am facing is that the data used in the chart must be an array but the type of data I have is an object. So how can I convert it to an array. The data I have :

Object {Normale: 1129, urgente: 153}

The array am trying to have would be something like this:

[['priorite', 'nb'], ['urgente', 1129],['normale', 153]]

Thank you,

3 个答案:

答案 0 :(得分:0)

var myArray = [];
angular.forEach(function(obj) {
    myArray.push({"priorite": obj.Normale, "nb": obj.urgente});
});

答案 1 :(得分:0)

You can use reduce on the Object.keys:

var o = {
  Normale: 1129,
  urgente: 153
};

var a = Object.keys(o).reduce((a, b) => a.concat({
  priorite: b,
  nb: o[b]
}), []);

console.log(a);

答案 2 :(得分:0)

Lodash很容易做到这一点。

  1. 使用toPairs方法将对象转换为对
  2. 使用Array.unshift方法在​​第一个位置插入['priorite', 'nb']
  3. 这就是全部! ;)
  4. 
    
    var obj = {Normale: 1129, urgente: 153};
    var arr = _.toPairs(obj);
    arr.unshift(['priorite', 'nb']);
    
    console.log(arr);
    
    <!doctype html>
    
    <html lang="en" ng-app="app">
    <head>
      <meta charset="utf-8">
      <script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
    </head>
    
    <body>
      
    </body>
    </html>
    &#13;
    &#13;
    &#13;

    您也可以通过这些方式按其价值(首先是紧急,最后是非常低)订购优先顺序:

    &#13;
    &#13;
    var obj = {VeryLow: 100, Normal: 500, Urgent: 1000, Low: 250};
    var arr = _.toPairs(obj);
    arr = arr.sort(function compare(a, b) {
      if (a[1] > b[1])
         return -1;
      if (a[1] < b[1])
         return 1;
      return 0;
    });
    arr.unshift(['priorite', 'nb']);
    
    console.log(arr);
    &#13;
    <!doctype html>
    
    <html lang="en" ng-app="app">
    <head>
      <meta charset="utf-8">
      <script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
    </head>
    
    <body>
    
    </body>
    </html>
    &#13;
    &#13;
    &#13;