javascript - 如何从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))
我在这里想念什么?
提前谢谢了。
解决方案
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);
推荐阅读
- python - 如何阻止 Pandas 从 csv 文件中删除封闭字符?
- javascript - 如何更改数组内对象的属性值
- colors - AppleScript 颜色检测
- arrays - 在 PostgreSQL 中对 bigint[] 列进行排序
- php - Symfony 5 NormalizerInterface 未找到
- reactjs - 复合组件 - React Typescript
- outlook-web-addins - Office 可扩展性沙箱 + 允许模式
- swift - Swift - 出现 VC B 后如何将数据从 VC A 传递到 B?
- php - 我想在每个帖子中显示帖子的用户名创建者
- elasticsearch - java.lang.NoSuchMethodError:org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder.setSource