Convert hard-coded data into automated data in Javascript Chart.js

I have a data variable that needs to be represented on a line chart in Chart.js in React app. I am showing train and test data on the same line chart.
The values for the train dataset and test dataset are as follows:
train: [369, 438, 329, 435, 359, 345, 406, 469, 457, 499, 352, 336, 480, 499, 354] //y-axis
test: [354, 354, 354, 354, 354] //y-axis

The values for the train dataset indices and test dataset indices are as follows:
train_idx: [0, 1, 2, 3, 4, 5,6 ,7 ,8 9, 10, 11, 12, 13, 14] //x-axis
test_idx: [14, 15, 16, 17, 18] //x-axis

I have hard-coded the values for now and the code looks as follows:

const [data, setData] = useState({
    labels: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
    datasets: [{
        label: 'Train Dataset',
        data: [{x: 0, y: 369},
               {x: 1, y: 438},
               {x: 2, y: 329},
               {x: 3, y: 435},
               {x: 4, y: 359},
               {x: 5, y: 345},
               {x: 6, y: 406},
               {x: 7, y: 469},
               {x: 8, y: 457},
               {x: 9, y: 499},
               {x: 10, y: 352},
               {x: 11, y: 336},
               {x: 12, y: 480},
               {x: 13, y: 499},
               {x: 14, y: 354}],
        //data: [369, 438, 329, 435, 359, 345, 406, 469, 457, 499, 352, 336, 480, 499, 354],
        borderColor: 'blue',
        
    }, {
        label: 'Test Dataset',
        data: [{x: 14, y: 354},
            {x: 15, y: 354},
            {x: 16, y: 354},
            {x: 17, y: 354},
            {x: 18, y: 354}],
        //data: [354, 354, 354, 354, 354],
        type: 'line',
        borderColor: 'purple',
        
    }],
    
})

From the above data, I get a graph that looks like this:
enter image description here

Now, I need the same graph but without hard-coding the values like above.
Please help me. The resulting graph without hard-coding the values needs to look like the picture.