在Angular 2中过滤数组以获取特定参数

时间:2016-12-08 10:08:56

标签: javascript arrays

我想过滤一个看起来像这样的对象数组

{
  "value_1": [
    {
      "ts": "2016-12-05T11:28:49+00:00",
      "value": 1
    },
    {
      "ts": "2016-12-05T11:28:55+00:00",
      "value": 1
    }
  ],
  "value_2": [
    {
      "ts": "2016-12-05T11:28:49+00:00",
      "value": 56.1
    },
    {
      "ts": "2016-12-05T11:28:55+00:00",
      "value": 56.08
    }
  ]
}

value并返回value应显示的所有内容:[1, 1, 56.1, 56.08]

这是最好的方法吗?

3 个答案:

答案 0 :(得分:2)

只是一些地图,reduce-fu



let obj = {
    "value_1": [{"ts": "2016-12-05T11:28:49+00:00", "value": 1},
        {"ts": "2016-12-05T11:28:55+00:00", "value": 1}],
    "value_2": [{"ts": "2016-12-05T11:28:49+00:00", "value": 56.1},
        {"ts": "2016-12-05T11:28:55+00:00", "value": 56.08}]
};

let result = Object.keys(obj).map(key => obj[key].map(ts => ts.value)).reduce((acc, value) => acc.concat(value),[]);

console.log(result);
console.log('isArray = '+Array.isArray(result));
result.forEach((item, index) => console.log(`result[${index}]=${item}`));




答案 1 :(得分:1)

您将需要一个解析函数,它将迭代递归数据对象。

类似的东西:

parseObject(obj: any): number[] {
  const _parse = (obj: any): number[] {
    if (!obj || typeof(obj) !== 'object') return [];

    const values = [];
    Object.keys(obj).forEach(k => {
      const o = obj[k];
      if (k === 'value' && !isNaN(o)) values.push(+o);
      if (typeof(o) === 'object') values.push(..._parse(o));
    });

    return values;
  }

  return _parse(obj);
}

live-demo:https://plnkr.co/edit/c4A0G6zGTa39kQNXyfhv?p=preview

答案 2 :(得分:1)

通过使用for-each也可以实现你的要求,看看下面的snippest



<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{final}}!</p>
  </body>
<script>
  var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = {
  "value_1": [
    {
      "ts": "2016-12-05T11:28:49+00:00",
      "value": 1
    },
    {
      "ts": "2016-12-05T11:28:55+00:00",
      "value": 1
    }
  ],
  "value_2": [
    {
      "ts": "2016-12-05T11:28:49+00:00",
      "value": 56.1
    },
    {
      "ts": "2016-12-05T11:28:55+00:00",
      "value": 56.08
    }
  ]
};
 $scope.final=[];
angular.forEach($scope.name,function(k,v){
 
 angular.forEach(k,function(x,y){
  $scope.final.push(x.value);
});
});
console.log($scope.final);

  
});

</script>
</html>
&#13;
&#13;
&#13;