Return child 匹配 JavaScript 中的嵌套循环

Return child that matches in nested loop in JavaScript

我想弄清楚如何在 React 的嵌套循环中 return child。数据 object 包含一个文档列表,每个文档包含一个文件列表。这是我目前所拥有的:

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

这几乎行得通,但问题是这里的匹配设置为匹配文件的文档,我希望将其更新为匹配文件..关于如何将其更改为 return 文件 object 而不是?

编辑:我只想 return 编辑第一个匹配项,然后跳出循环。

一个选项是在该选项上使用 Array.prototype.flat() first to get all your files in a single array, then call 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 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;
}

如果您需要所有匹配的文件,请使用 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);

你可以这样做:

const documents = [{files: [{fileType: 'jpeg'}, {fileType: 'docx'}]}, {files: [{fileType: 'docx'}]}, {files: [{fileType: 'docx'}, {fileType: 'pdf'}]}, {files: [{fileType: 'jpeg'}]}];
let index;
const match = documents.find((document) =>
  document.files.some(
    // store the index of the matched fileType
    (file, i) => file.fileType === 'pdf' ? (index = i, true) : false,       
  ),
);
console.log(match.files[index]);

或使用基本的 for...of

const documents = [{files: [{fileType: 'jpeg'}, {fileType: 'docx'}]}, {files: [{fileType: 'docx'}]}, {files: [{fileType: 'docx'}, {fileType: 'pdf'}]}, {files: [{fileType: 'jpeg'}]}];
let matchBreak;

Doc: for(let document of documents) {
  for(let file of document.files) {
    if(file.fileType === 'pdf') {
     matchBreak = file;
     break Doc;
    }
  }
}

console.log(matchBreak);

function findFile(documents) {
  for(let document of documents) {
    for(let file of document.files) {
      if(file.fileType === 'pdf') {
       return file;
      }
    }
  }
}

const matchReturn = findFile(documents);
console.log(matchReturn);