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

时间:2018-12-10 09:41:12

标签: javascript arrays object distinct

我在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))

我在这里想念什么?

非常感谢。

1 个答案:

答案 0 :(得分:4)

您在回调.map()的过程中使用了拼写错误的参数,即将thing替换为event。您也可以使用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);

相关问题