如何根据扩展名修改数组

时间:2019-05-21 10:48:14

标签: javascript

我想修改array中的object,以根据文件扩展名将其sub-array'文件'分为两类。

  • img[](以.jpg结尾的文件列表)
  • pdf[](以.pdf结尾的文件列表)

var test = [ 
  {
  name: 'ter3',
  files: ['dsf.jpg', 'test.jpg', 'lolwa.pdf']
}, {
   name: 'test2',
  files: ['te.jpg', 'fgfd.jpg', 'lolwa.pdf']
}
]

test.filter(item => {
   item.files.filter(file => {
       if(file.indexOf('jpg') !== -1) {
         console.log(file)
       }

    })
})

console.log(test)

我想将上面的数组修改为此。

var test = [ 
  {
  name: 'ter3',
  files: ['dsf.jpg', 'test.pdf', 'lolwa.jpg'],
   img: ['dsf.jpg', 'lolwa.jpg'],
   pdf: ['test.pdf']
}, {
   name: 'test2',
  files: ['te.jpg', 'fgfd.jpg', 're.pdf'],
  img: ['te.jpg', 'fgfd.jpg'],
  pdf: ['re.pdf']
}
]

7 个答案:

答案 0 :(得分:2)

使用array.map()进行尝试,如以下代码片段所示:

var test = [ 
  {
  name: 'ter3',
  files: ['dsf.jpg', 'test.jpg', 'lolwa.pdf']
}, {
   name: 'test2',
  files: ['te.jpg', 'fgfd.jpg', 'lolwa.pdf']
}
]

test.map(item => { //Map the array
  item.img = [] //Initialize the img and pdf arrays
  item.pdf = []
  
  item.files.forEach(file => { //Add to the img and pdf array accordingly
    if(file.endsWith('.jpg')) {
      item.img.push(file)
    } else if (file.endsWith('.pdf')) {
      item.pdf.push(file)
    }
  })
    
   return item
})

console.log(test)

答案 1 :(得分:2)

这应该使用正则表达式工作。它使用修饰符x[slice_arrays] (不区分大小写)来匹配以i.JPG结尾的文件。

.PDF

答案 2 :(得分:1)

您可以执行以下操作:

var test = [ 
  {
  name: 'ter3',
  files: ['dsf.jpg', 'test.jpg', 'lolwa.pdf']
}, {
   name: 'test2',
  files: ['te.jpg', 'fgfd.jpg', 'lolwa.pdf']
}
];

test.forEach(obj => {
  obj.files.forEach(file => {
    const fileExtension = file.substring(file.lastIndexOf('.') + 1);
    obj[fileExtension] = obj[fileExtension] || [];
    obj[fileExtension].push(file);
  });
});

console.log(test);

这将创建密钥,具体取决于文件扩展名,并且不限于诸如jpgpng这样的硬编码值。它还应该考虑一些边缘情况,例如像file.pdf.jpg

这样的文件名

答案 3 :(得分:0)

尝试一下。它还将jpg和pdf视为最后一个字符串。所以像ijpg.pdf这样的东西会匹配为pdf,而不是jpg

<FORM METHOD="post" ACTION="update.php">
    <div class="input-group">
        <label>Member Id</label>
        <INPUT TYPE="text" name="memberID" SIZE="30">
    </div>
    <div class="input-group">
        <label>First Name</label>
        <INPUT TYPE="text" name="MFirst" SIZE="30">  
    </div> 
    <div class="input-group">
        <label>Last Name</label>
        <INPUT TYPE="text" name="MLast" SIZE="30">
    </div>   
    <div class="input-group">
        <label>Street Name</label>
        <INPUT TYPE="text" name="Street" SIZE="30">     
    </div>
    <div class="input-group">
        <label>Street Number</label>
        <INPUT TYPE="number" name="number" min=0 SIZE="30">
    </div>  
    <div class="input-group">
        <label>Postal Code</label>
        <INPUT TYPE="number" name="postalCode" min=0 SIZE="30"> 
    </div>
    <div class="input-group">
        <label>Birth Day</label>
        <INPUT TYPE="date" name="Mbirthdate" SIZE="30">
    </div>
    <button class="btn" TYPE="submit" name="submit">Submit Info </button>
    <button class="btn" TYPE="reset" name="Reset">Reset </button>
</FORM>

https://jsbin.com/lanukelugu/1/edit?js,console

答案 4 :(得分:0)

您可以为每个文件扩展名使用规则的“字典”,如下所示:

var test = [
  {
    name: "ter3",
    files: ["dsf.jpg", "test.jpg", "lolwa.pdf"]
  },
  {
    name: "test2",
    files: ["te.jpg", "fgfd.jpg", "lolwa.pdf"]
  }
];

const rules = {
  jpg: "img",
  pdf: "pdf"
};

test.forEach(obj => {
  obj.files.forEach(file => {
    const extension = rules[file.substr(file.lastIndexOf('.') + 1)];
    obj[extension] != undefined
      ? obj[extension].push(file)
      : (obj[extension] = [file]);
  });
});
console.log(test);

答案 5 :(得分:0)

您可以使用Array.map()RegExp.test()

var test = [ 
  {
  name: 'ter3',
  files: ['dsf.jpg', 'test.jpg', 'lolwa.pdf']
}, {
   name: 'test2',
  files: ['te.jpg', 'fgfd.jpg', 'lolwa.pdf']
}
];

const arr = test.map(obj => ({
  ...obj,
  img: obj.files.filter(f => /\.jpg$/.test(f)),
  pdf: obj.files.filter(f => /\.pdf$/.test(f))
}));

console.log(arr);

答案 6 :(得分:0)

// The array to process.
var input = [ 
  {
  name: 'ter3',
  files: ['dsf.jpg', 'test.jpg', 'lolwa.pdf']
}, {
   name: 'test2',
  files: ['te.jpg', 'fgfd.jpg', 'lolwa.pdf']
}
],
// An array with file type. This makes it easy to add new types.
fileTypes = [
  {
    id: 'pdf',
    predicate: /.pdf$/i
  },
  {
    id: 'img',
    predicate: /.(jpg|bmp)$/i
  }
];

// Create a new array where each entry of the input array is enriched with
// a property per file type listing the files that match that file type.
var output = input.map(entry => {
  // Create a copy of the current object so the original object
  // is not modified.
  const modifiedEntry = {...entry};
  
  // Iterate over all the file types. For each entry, add a property with the
  // name equal to the ID and filter the files based on the predicate.
  fileTypes.forEach(fileType => {
    modifiedEntry[fileType.id] = entry.files.filter(item => fileType.predicate.test(item))
  });
  
  // Return the modified entry.
  return modifiedEntry;
});
  
// Log the input, this should be unchanged from when we started.  
console.log('--[ input ]--');
console.log(input);
// Log the output.  
console.log('--[ output ]--');
console.log(output);