首页 文章

如何从Javascript中的对象列表中获取不同的年份

提问于
浏览
3

我想从 createdOn 值返回不同年份的列表:

我尝试了以下但它返回一个空数组:

const things = [{
    "id": 1,
    "title": "First thing",
    "createdOn": "2017-12-07T15:44:50.123"
  },
  {
    "id": 2,
    "title": "Second thing",
    "createdOn": "2018-05-07T09:10:24.123"
  },
  {
    "id": 3,
    "title": "Third thing",
    "createdOn": "2018-12-07T12:07:50.123"
  },
  {
    "id": 4,
    "title": "Forth thing",
    "createdOn": "2018-12-07T16:39:29.123"
  }
]

console.log(things.map(thing => new Date(thing.createdOn).getFullYear()).filter((value, index, self) => self.indexOf(value) === index))

我在这里想念的是什么?

提前谢谢了 .

1 回答

  • 3

    你在 .map() 的回调中使用拼写错误的参数,即用 event 替换 thing . 您也可以使用 Set 获取唯一值:

    const data = [
      {"id": 1, "title": "First thing", "createdOn": "2017-12-07T15:44:50.123"}, 
      {"id": 2, "title": "Second thing", "createdOn": "2018-05-07T09:10:24.123"}, 
      {"id": 3, "title": "Third thing", "createdOn": "2018-12-07T12:07:50.123"}, 
      {"id": 4, "title": "Forth thing", "createdOn": "2018-12-07T16:39:29.123"}
    ];
    
    const result = [...new Set(data.map(event => new Date(event.createdOn).getFullYear()))];
    
    console.log(result);
    

相关问题