我正在尝试过滤一个对象数组,以找到带有图像扩展名的所有值,然后将找到的值推送到自己的数组中。
示例: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)
}
}
&#13;
答案 0 :(得分:1)
试试这个,我遍历对象并检查对象是否具有属性作为对象,然后遍历它并添加,如果找到任何图像。
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);
&#13;
答案 1 :(得分:0)
// 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);
}
});
一些参考链接:
How do you access the matched groups in a JavaScript regular expression?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce