我有一个用PHP json_encode函数创建的JSON:
$json = [{"title":"test1","date":"2019, 12, 27"},{"title":"test2","date":"2019, 11, 19"}];
我想将这些字段映射到日历数据源字段:https://year-calendar.github.io/rc-year-calendar/examples如何正确执行此操作?
我需要什么:
<script type="text/javascript">
const calendar = new Calendar('#calendar', {
dataSource: [
{
startDate: new Date(2019, 12, 27),
name: 'test1'
},
{
startDate: new Date(2019, 11, 19),
name: 'test2'
},
],
});
</script>
我尝试过的事情:
$json = [{"title":"test1","date":"2019, 12, 27"},{"title":"test2","date":"2019, 11, 19"}];
<script type="text/javascript">
var json = <?php echo $json; ?>;
const calendar = new Calendar('#calendar', {
dataSource: [
return json.map(r => ({
startDate: new Date(r.date),
name: r.title,
}));
],
});
</script>
答案 0 :(得分:0)
您可以执行以下操作:
const calendarArray = [{"title":"test1","date":"2019, 12, 27"},{"title":"test2","date":"2019, 11, 19"}];
const dataSource = calendarArray.map((element) => {
return {
startDate: new Date(element.date),
name: element.title
}
});
const calendar = new Calendar("#calendar", {dataSource: dataSource})
<script src="https://unpkg.com/js-year-calendar@latest/dist/js-year-calendar.min.js"></script>
<div id="calendar"></div>
答案 1 :(得分:0)
您正在尝试在数组内使用map。 .map()返回会基于原始数组创建一个新的值数组。您正在将数据源定义为数组,并试图像函数一样使用它,这就是为什么它不起作用的原因
尝试一下
const calendarData = json.map(r => ({
startDate: new Date(r.date),
name: r.title,
}));
const calendar = new Calendar('#calendar', {
dataSource: calendarData
});
或在线
const calendar = new Calendar('#calendar', {
dataSource: json.map(r => ({
startDate: new Date(r.date),
name: r.title,
}));,
});