Return child that matches in nested loop in JavaScript

I’m trying to figure out how I can return the child in a nested loop in React. The data object contains a list of documents which each contains a list of files. This is what I have so far:

 const match = (data.documents.find((document) =>
        document.files.find(
            (file) => file.fileType === 'pdf',       
        ),
    );

This almost works, but the problem is that here match is set to the document of the matching file, and I want it to be updated to the matching file .. Any input on how I can change it to return the file object instead?

Edit: I only want the first match to be returned and then break out of the loops.

Answer

One option would be to use Array.prototype.flat() first to get all your files in a single array, then call Array.prototype.find() on that one to get the first match:

const documents = [{
  files: [
    { name: 'a.png', fileType: 'png' },
    { name: 'b.png', fileType: 'png' },
    { name: 'c.png', fileType: 'png' },
  ],
}, {
  files: [
    { name: 'd.png', fileType: 'png' },
    { name: 'e.png', fileType: 'png' },
    { name: 'f.pdf', fileType: 'pdf' },
  ],
}, {
  files: [
    { name: 'g.png', fileType: 'png' },
    { name: 'h.pdf', fileType: 'pdf' },
    { name: 'i.png', fileType: 'png' },
  ],
}]

const files = documents.map(doc => doc.files).flat();

console.log(files);

const match = files.find(file => file.fileType === 'pdf');

console.log(match);
.as-console-wrapper {
  max-height: 100% !important;
}

If you need all the files that match, then use Array.prototype.filter() instead of Array.prototype.find():

const documents = [{
  files: [
    { name: 'a.png', fileType: 'png' },
    { name: 'b.png', fileType: 'png' },
    { name: 'c.png', fileType: 'png' },
  ],
}, {
  files: [
    { name: 'd.png', fileType: 'png' },
    { name: 'e.png', fileType: 'png' },
    { name: 'f.pdf', fileType: 'pdf' },
  ],
}, {
  files: [
    { name: 'g.png', fileType: 'png' },
    { name: 'h.pdf', fileType: 'pdf' },
    { name: 'i.png', fileType: 'png' },
  ],
}]

const matches = documents.map(doc => doc.files).flat().filter(file => file.fileType === 'pdf');

console.log(matches);