简体   繁体   English

下划线嵌套对象的过滤器数组

[英]underscore filter array of nested objects

I have the following array of objects: 我有以下对象数组:

[{key: "test", values: [{key: "2015-05", values: [{1:2}, {3:4}]}, {}], ...]

I want to filter by the key value to only be left with values after a certain date. 我想key值过滤,只保留特定日期之后的值。

I currently have this, but the resulting the structure is wrong 我目前有这个,但是结果结构是错误的

_.map(temp1, function(value, key) { return _.filter(value.values, function(v) { return v.key > "2015-05"; }); });

Slight improvement on Frank's answer : 弗兰克的答案略有改善:

 var data = [ { key: "1", values: [ {key: "2014-05", values: [{1:2}, {3:4}]}, {key: "2015-05", values: [{1:2}, {3:4}]}, {key: "2013-05", values: [{1:2}, {3:4}]} ] }, { key: "2", values: [ {key: "2014-05", values: [{1:2}, {3:4}]}, {key: "2015-05", values: [{1:2}, {3:4}]}, {key: "2013-05", values: [{1:2}, {3:4}]} ] } ]; var a = _.map(data, (d) => { d.values = _.filter(d.values, (v) => v.key > "2014"); return d; }); console.log(a); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

No need to parse this date format, a string comparison will suffice. 无需解析此日期格式,字符串比较就足够了。 Important to note, despite the _.map operation, this will modify the original. 需要注意的重要一点是,尽管进行了_.map操作,但仍会修改原始文件。

Something like this maybe? 像这样的东西?

var data = [
  {
    key: "1", 
    values: [
      {key: "2014-05", values: [{1:2}, {3:4}]},
      {key: "2015-05", values: [{1:2}, {3:4}]},
      {key: "2013-05", values: [{1:2}, {3:4}]}
    ]
  },
  {
    key: "2", 
    values: [
      {key: "2014-05", values: [{1:2}, {3:4}]},
      {key: "2015-05", values: [{1:2}, {3:4}]},
      {key: "2013-05", values: [{1:2}, {3:4}]}
    ]
  }
];

var a = _.map(data, (d) => {
  d.values = _.filter(d.values, (v) => {
    return Date.parse(v.key) > Date.parse("2014");
  });
  return d;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM