首页 > 解决方案 > 如何从Javascript中的对象列表中获取不同的年份

问题描述

我在 Javascript 中有以下对象,我想从该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))

我在这里想念什么?

提前谢谢了。

标签: javascriptarraysobjectdistinct

解决方案


You are using a misspelled argument in callback to the .map() i.e replace thing with event. You may also use Set to get the unique values:

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);


推荐阅读