2

Help, I'm using filepond and I want to put the files uploaded inside an array from a declared array. I'm really sorry, my first time to use File Pond library. This is my sample code.

let data_to_review = []

$('.step:nth-child(1) .form-control').each(function(index, element){
   if($(element).hasClass('required')) {
       nextstep = checkForm($(element).attr('id'))
   }
   data_to_review[$(element).attr('id')] = $(element).val() 
})

$('.file_uploader').on('FilePond:addfile', function(e) {
     console.log('file added event', e);
     testData()
});

function testData() {
   let files = $('.file_uploader').filepond('getFiles');
   $(files).each(function (index) {
       data_to_review['files'][index] = files[index].file
   });
   console.log(data_to_review)
}

Everytime I used the code above, it gives me Uncaught TypeError: Cannot set properties of undefined (setting '0')

My desired array will be like this: [{ files: [ file one, file two ] }] Thanks in advance!

  • 2
    Have you tried to add console.log() and see if everything is as you expect. Is index really the index? Are `Files` in `data_to_review['files']` avaible? and so on. Also `[files: [ file one, file two ]]` is not possible, It would have to be `{files: [ file one, file two ]}` – Carsten Løvbo Andersen Apr 20 '23 at 07:05
  • 1
    Sorry about that, I corrected it: {files: [ file one, file two ]} –  Apr 20 '23 at 07:11
  • 2
    What is `data_to_review`? Does it have a key named `files` already? If not, initialize that first: `data_to_review = { files: [] }` – InSync Apr 20 '23 at 07:12
  • 1
    I think I must do an ```array.push()``` function for this, I think it only accept one value like ```data_to_review['files'] = files[index].file –  Apr 20 '23 at 07:13

2 Answers2

0

{ files: [ file one, file two ] } is not an array but an object.
Well, declare data_to_review as an object then set its property files as an array containings the files you want.

// declare data_to_review as an empty object
let data_to_review = {}

function test() {
     let files = $('.file_uploader').filepond('getFiles');
     data_to_review['files'] = [...files].map(f => f.file)
     console.log(data_to_review)
 }

Another solution is to define the files property when declaring data_to_review then push each file inside.

// declare data_to_review as an empty object
let data_to_review = { files: [] }

function test() {
     let files = $('.file_uploader').filepond('getFiles');
     $(files).each(function (index) {
         data_to_review['files'].push(files[index].file)
     });
     console.log(data_to_review)
 }
nem0z
  • 1,060
  • 1
  • 4
  • 17
0

You need to set an empty to array in your array of object in order to have it read by your function.