筛选具有图像扩展名的字符串的对象值数组



我正在尝试过滤对象数组以查找具有图像扩展名的所有值,然后将找到的值推送到它们自己的数组中。示例:imageArray = ["steve.jpg", "funimage1.jpg", "coolimage2.png","greatimage3.svg", "jimmysavatar.jpg" ...] .

这是一个要测试的jsfiddle:https://jsfiddle.net/25pmwsee/

const myArray = [{
  "prepend": false,
  "name": "steve",
  "avatar": "steve.jpg",
  "imgs": [
    "funimage1.jpg",
    "coolimage2.png",
    "greatimage3.svg"
  ]
},
{
  "prepend": false,
  "name": "jimmy",
  "avatar": "jimmysavatar.jpg",
  "imgs": [
    "realimage1.jpg",
    "awesomeimage2.png",
    "coolimage3.svg"
  ]
}]
const extensions = [".jpg", ".png", ".svg"];
let imageArray = [];
// search in array for extension then push key to array
for (let i = 0; i < extensions.length; i++) {
  if ( extensions[i] in myArray ) {
    imageArray.push(image)
  }
}

试试这个,我遍历对象并检查对象是否具有对象属性,然后遍历它并在找到任何图像时添加。

const myArray = [{
  "prepend": false,
  "name": "steve",
  "avatar": "steve.jpg",
  "imgs": [
    "funimage1.jpg",
    "coolimage2.png",
    "greatimage3.svg"
  ]
},
{
  "prepend": false,
  "name": "jimmy",
  "avatar": "jimmysavatar.jpg",
  "imgs": [
    "realimage1.jpg",
    "awesomeimage2.png",
    "coolimage3.svg"
  ]
}]
const extensions = [".jpg", ".png", ".svg"];
let imageArray = [];
// search in array for extension then push key to array
function iterate(obj){
  for(var x in obj){
    //console.log(typeof(obj[x]));
    if(typeof(obj[x])==='object'){
      iterate(obj[x]);
    }
    else if (obj.hasOwnProperty(x)){
        extensions.forEach(function(e){
            if(typeof(obj[x])==='string' && obj[x].endsWith(e))
              imageArray.push(obj[x]);
        })
    }
  } 
}
myArray.forEach(function(x){iterate(x)})
console.log(imageArray);

// regular expression to match a file extension and capture it
const extensionRegex = /.([a-z]+)$/
// map of allowed extensions; indexing by any not listed will be falsy (undefined)
const allowedExtensions = {
    'jpg': true,
    'png': true,
    'svg': true
}
// grab each user's avatar
let avatars = myArray.map(function (user) {
    return user.avatar
})
// takes all the imgs arrays and flatten them down to an array of strings
let imgs = myArray.map(function (user) {
    return user.imgs
}).reduce(function (flattened, images) {
    return flattened.concat(images)
}, [])
avatars.concat(imgs).forEach(function (imageName) {
    // if imageName is undefined or empty, use empty string instead
    // since we know that will fail the allowedExtensions check and not push
    let extension = (imageName || '').match(extensionRegex)[1]
    if (allowedExtensions[extension]) {
        imageArray.push(imageName);
    }
});

一些参考链接:

如何在 JavaScript 正则表达式中访问匹配的组?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

最新更新