我需要将一个数组转换为另一个数组,但找不到执行此操作的好方法。一条错误消息告诉我我不能插入 found[0].children
,但我觉得我做的一切都是错误和肮脏的;你能告诉我你是如何处理这类问题的吗?
我想转换数组:
const input =
[
{value: "29-08-2020 16:00", visible: 0},
{value: "29-08-2020 16:30", visible: 1},
{value: "29-08-2020 17:00", visible: 0},
{value: "30-08-2020 15:00", visible: 1},
{value: "30-08-2020 15:30", visible: 1}
];
进入数组:
const output =
[
{
id: '29/08/2020',
label: '29/08/2020',
children:
[
{
id: '16:00',
label: '16:00',
isDisabled: true
},
{
id: '16:30',
label: '16:30'
},
{
id: '17:00',
label: '17:00',
isDisabled: true
}
],
},
{
id: '30/08/2020',
label: '30/08/2020',
children:
[
{
id: '15:00',
label: '15:00'
},
{
id: '15:30',
label: '15:30'
}
]
}
];
这是我尝试过的,但我对这个想法一点都不满意,这似乎不是一个好方法......
function dateoptions(dateslist) {
var options: any[] = [];
dateslist.forEach(element => {
var tab = element.value.split(' ');
var dt = tab[0];
var time = tab[1];
var found = options.filter(opt=> opt.id==dt);
if (found.length>0) {
// I can't do this:
found[0].children.push({
'id': time,
'label': time,
disabled: element.visible==0
});
}
else {
options.push({
'id': dt,
'label': dt,
'children': {'id':time, 'label': time, disabled: element.visible==0}
});
}
});
return options;
}
最佳答案
您可以减少数组并迭代同一组的结果集。
const
data = [{ value: "29-08-2020 16:00", visible: 0 }, { value: "29-08-2020 16:30", visible: 1 }, { value: "29-08-2020 17:00", visible: 0 }, { value: "30-08-2020 15:00", visible: 1 }, { value: "30-08-2020 15:30", visible: 1 }],
result = data.reduce((r, { value, visible }) => {
let [date, time] = value.split(' '),
temp = r.find(q => q.id === date);
if (!temp) r.push(temp = { id: date, label: date, children: [] });
temp.children.push({ id: time, label: time, ...(!visible && { isDisabled: !visible }) });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何在 JavaScript 中用对象转换数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62672902/