说我有一个数组,
this.list = [
{id:1, task: 'circle', janstartdate: '2017-01-01', febstartdate: '2017-02-01' },
{id:2, task: 'square', janstartdate: '2017-01-06', febstartdate: '2017-02-11' },
{id:3, task: 'triangle', janstartdate: '2017-01-10', febstartdate: '2017-02-21' }
]
是否可以使用Javascript获得一个类似于下面的新列表的新数组?
我不确定下面的代码片段是否正确;但基本上,我想按“ janstartdate”列重新组合原始数组,然后按新数组中同一级别的“ febstartdate”进行重新组合。
这可能吗?
输出为:
newlist = [
{
month:
{'january':
[
2017-01-01: { id:1, task: 'circle'},
2017-01-06: { id:2, task: 'square'},
2017-01-10: { id:3, task: 'triangle'}
],
month:
{'february':
[
2017-02-01: { id:1, task: 'circle'},
2017-02-11: { id:2, task: 'square'},
2017-02-21: { id:3, task: 'triangle'}
],
}
答案 0 :(得分:0)
您可以做这样的事情
list = [
{id: 1,task: 'circle',janstartdate: '2017-01-01',febstartdate: '2017-02-01'},
{id: 2,task: 'square',janstartdate: '2017-01-06',febstartdate: '2017-02-11'},
{id: 3,task: 'triangle',janstartdate: '2017-01-10',febstartdate: '2017-02-21'}
]
newList = {
january: {},
february: {}
}
list.map(item => {
newList.january[item.janstartdate] = {
id: item.id,
task: item.task
}
newList.february[item.febstartdate] = {
id: item.id,
task: item.task
}
})
console.log(newList)
在january
中使用february
和list
可能有助于减少重复
像这样:
list = [
{id:1, task: 'circle', january: '2017-01-01', february: '2017-02-01' },
{id:2, task: 'square', january: '2017-01-06', february: '2017-02-11' },
{id:3, task: 'triangle', january: '2017-01-10', february: '2017-02-21' }
]
newList = {}
months = ["january", "february"]
list.map(item => {
for (let month of months) {
if (!newList[month]) {
newList[month] = {}
}
newList[month][item[month]] = {
id: item.id,
task: item.task
}
}
})
console.log(newList)
仅当每个数据都是唯一的时,这些方法才有效;如果它们不是唯一的,则仅保留最后一个数据。