我在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))
我在这里想念什么?
非常感谢。
答案 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);