代码之家  ›  专栏  ›  技术社区  ›  The Old County

JavaScript-从嵌套严重的数组中的查找创建逗号分隔的字符串

  •  0
  • The Old County  · 技术社区  · 4 年前

    我正在构建一个拖放应用程序,该应用程序提供了一个多维数组,其中包含支持的文件类型和标题,这些文件类型和图标可以在图例中使用。拖放操作会拾取一个具有特定mime类型的accept数组——我需要以简单的方式向用户显示允许的文件类型——因此返回一个逗号分隔的字符串——jpg、pdf

    循环遍历多维数组以找到表单中的键以完成此任务的最佳方法是什么?

      getAcceptedFileTypes(){
    
    let supportedFiles = [{
      "images": {
        "icon": <ImageIcon />,
        "formats": [{"png": "image/png"}, {"jpeg": "image/jpeg"}],
      }
    },{
      "compressed_files": {
        "icon": <DescriptionIcon />,
        "formats": [{"zip": "application/x-zip-compressed"}, {"rar": "application/x-rar-compressed"}],
      }
    },{
      "documents": {
        "icon": <FileCopyIcon />,
        "formats": [{"pdf": "application/pdf"}, {"docx": "application/msword"}, {"doc": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}],
      }
    }];
    
    let accept = ["application/pdf","image/jpeg"]
    
        console.log("supportedFiles", supportedFiles);
        console.log("accept", accept);
    
    
        let acceptedFiles = "jpeg, pdf";
    
        return (
          acceptedFiles
        )
      }
    
    0 回复  |  直到 4 年前
        1
  •  2
  •   secan    4 年前

    你可以这样做:

    let supportedFiles = [{
      "images": {
        "icon": "<ImageIcon />",
        "formats": [{
          "png": "image/png"
        }, {
          "jpeg": "image/jpeg"
        }],
      }
    }, {
      "compressed_files": {
        "icon": "<DescriptionIcon />",
        "formats": [{
          "zip": "application/x-zip-compressed"
        }, {
          "rar": "application/x-rar-compressed"
        }],
      }
    }, {
      "documents": {
        "icon": "<FileCopyIcon />",
        "formats": [{
          "pdf": "application/pdf"
        }, {
          "docx": "application/msword"
        }, {
          "doc": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        }],
      }
    }];
    
    let accept = ["application/pdf", "image/jpeg"];
    
    const acceptedFiles = supportedFiles.reduce((acc, item) => {
      const subItem = Object.values(item)[0];
    
      subItem.formats.forEach((format, index) => {
        if (accept.indexOf(Object.values(format)[0]) > -1) {
          acc.push(Object.keys(subItem.formats[index])[0]);
        }
      });
    
      return acc;
    }, []).join(', ');
    
    
    //test
    console.log(acceptedFiles);
        2
  •  0
  •   mplungjan    4 年前

    你是说这个?

    const getAcceptedFileTypes = () => {
    
      let supportedFiles = [{
        "images": {
          "icon": `<ImageIcon />`,
          "formats": [{
            "png": "image/png"
          }, {
            "jpeg": "image/jpeg"
          }],
        }
      }, {
        "compressed_files": {
          "icon": `<DescriptionIcon />`,
          "formats": [{
            "zip": "application/x-zip-compressed"
          }, {
            "rar": "application/x-rar-compressed"
          }],
        }
      }, {
        "documents": {
          "icon": `<FileCopyIcon />`,
          "formats": [{
            "pdf": "application/pdf"
          }, {
            "docx": "application/msword"
          }, {
            "doc": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
          }],
        }
      }];
    
    
    
      let acceptedFiles = supportedFiles.flatMap(file => file[Object.keys(file)[0]].formats)
    
      return (
        acceptedFiles
      )
    }
    
    console.log(getAcceptedFileTypes())
    
    console.log(getAcceptedFileTypes().map(entry => Object.keys(entry)[0]).join(","))
        3
  •  0
  •   Abishek Kumar    4 年前

    也许想试试这个

    let supportedFiles = [{
      "images": {
        "icon": '<ImageIcon />',
        "formats": [{"png": "image/png"}, {"jpeg": "image/jpeg"}],
      }
    },{
      "compressed_files": {
        "icon": '<DescriptionIcon />',
        "formats": [{"zip": "application/x-zip-compressed"}, {"rar": "application/x-rar-compressed"}],
      }
    },{
      "documents": {
        "icon": '<FileCopyIcon />',
        "formats": [{"pdf": "application/pdf"}, {"docx": "application/msword"}, {"doc": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}],
      }
    }];
    
    let acceptedFiles=[];
    supportedFiles.forEach((fileType)=>{
      Object.keys(fileType).forEach(key=>{
        fileType[key].formats.forEach(format=>{
          acceptedFiles.push(Object.keys(format));
       })
     })
    })
    console.log(acceptedFiles.join(","))

    如果你改变结构,那么:

    let supportedFilesObj ={
      "images": {
        "icon": '<ImageIcon />',
        "formats": [{"png": "image/png"}, {"jpeg": "image/jpeg"}],
      },
      "compressed_files": {
        "icon": '<DescriptionIcon />',
        "formats": [{"zip": "application/x-zip-compressed"}, {"rar": "application/x-rar-compressed"}],
      },
      "documents": {
        "icon": '<FileCopyIcon />',
        "formats": [{"pdf": "application/pdf"}, {"docx": "application/msword"}, {"doc": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}],
      }
    };
    
    let acceptedFiles=[];
    Object.keys(supportedFilesObj).forEach((key)=>{
        supportedFilesObj[key].formats.forEach(format=>{
          acceptedFiles.push(Object.keys(format));
       })
    })
    console.log(acceptedFiles.join(","))
        4
  •  0
  •   timlg07    4 年前

    这是一个使用3个嵌套for循环的简单解决方案。

    function getAcceptedFileExtensions() {
        let acceptedExtensions = [];
    
        for (let fileTypeObject of supportedFiles) {
            for (let fileTypeKey of Object.keys(fileTypeObject)) {
                for (let extensionPair of fileTypeObject[fileTypeKey].formats) {
                    acceptedExtensions.push(Object.keys(extensionPair)[0]);
                }
            }
        }
    
        return acceptedExtensions;
    }
    
    console.log(getAcceptedFileExtensions().toString());
    

    数据结构有点奇怪,因为它包含一个包含一个键的对象数组,该键似乎是每个对象的名称,而不是直接具有不同文件类型类别的对象。因此,第二个循环可以缩短为 Object.keys(fileTypeObject)[0] :

    const supportedFiles = [
        {
            "images": {
                "icon": "<ImageIcon />",
                "formats": [
                    { "png": "image/png" }, 
                    { "jpeg": "image/jpeg" }
                ],
            }
        }, 
        {
            "compressed_files": {
                "icon": "<DescriptionIcon />",
                "formats": [
                    { "zip": "application/x-zip-compressed" }, 
                    { "rar": "application/x-rar-compressed" }
                ],
            }
        }, 
        {
            "documents": {
                "icon": "<FileCopyIcon />",
                "formats": [
                    { "pdf": "application/pdf" }, 
                    { "docx": "application/msword" }, 
                    { "doc": "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }
                ],
            }
        }
    ];
    
    
    function getAcceptedFileExtensions() {
        let acceptedExtensions = [];
    
        for (let fileTypeObject of supportedFiles) {
            let fileTypeKey = Object.keys(fileTypeObject)[0];
            for (let extensionPair of fileTypeObject[fileTypeKey].formats) {
                acceptedExtensions.push(Object.keys(extensionPair)[0]);
            }
        }
    
        return acceptedExtensions;
    }
    
    console.log(getAcceptedFileExtensions().toString());
        5
  •  0
  •   adiga    4 年前

    如果这是一个重复操作,您可以创建一个映射器对象,将每个MIME类型映射到其文件扩展名

    const mapper = {}
    
    for (const file of supportedFiles) {
      const { formats } = Object.values(file)[0]
      for (const format of formats) {
        const [key, value] = Object.entries(format)[0]
        mapper[value] = key;
      }
    }
    
    function getAcceptedFiles(accept, mapper) {
      return accept.map(t => mapper[t])
    }
    

    映射器对象:

    {
      "image/png": "png",
      "image/jpeg": "jpeg",
      "application/x-zip-compressed": "zip",
      "application/x-rar-compressed": "rar",
      "application/pdf": "pdf",
      "application/msword": "docx",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "doc"
    }
    

    以下是一个片段:

    const supportedFiles=[{images:{icon:"",formats:[{png:"image/png"},{jpeg:"image/jpeg"}],}},{compressed_files:{icon:"",formats:[{zip:"application/x-zip-compressed"},{rar:"application/x-rar-compressed"}],}},{documents:{icon:"",formats:[{pdf:"application/pdf"},{docx:"application/msword"},{doc:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}],}}];
    
    const mapper = {}
    
    for (const file of supportedFiles) {
      const { formats } = Object.values(file)[0]
      for (const format of formats) {
        const [key, value] = Object.entries(format)[0]
        mapper[value] = key;
      }
    }
    
    function getAcceptedTypes(accept, mapper) {
      return accept.map(t => mapper[t])
    }
    
    console.log( getAcceptedTypes( ["application/pdf","image/jpeg"], mapper) )
    console.log( getAcceptedTypes( ["application/x-rar-compressed"], mapper) )