从数据库中我得到:
"Data": [{
"mainData": [{
"_id": ObjectId("5ab63b22d012ea2bc0bb7e9b"),
"date": "2018-03-24"
}],
"files": [
{
"_id": ObjectId("5ab63b22d012ea2bc0bb7e9d"),
"filename": "file-1521892130284.png",
"path": "uploads\\file-1521892130284.png"
},
{
"_id": ObjectId("5ab63b22d012ea2bc0bb7e9c"),
"filename": "file-1521892130285.png",
"path": "uploads\\file-1521892130285.png"
}
]
}]
但我需要像这样在上面进行转换:
this.galleryImages = [
{
small: 'file-1521892130284.png'
},
{
small: 'file-1521892130285.png'
}
];
如何更好地迭代某些文件路径并将其完全按照需求图库图像对象推送? galleryImages - 来自 Angular 的 ngx-gallery。
最佳答案
const ObjectId = (v) => v; // dummy implementation
const dbResponse = {"Data": [{
"mainData": [{
"_id": ObjectId("5ab63b22d012ea2bc0bb7e9b"),
"date": "2018-03-24"
}],
"files": [
{
"_id": ObjectId("5ab63b22d012ea2bc0bb7e9d"),
"filename": "file-1521892130284.png",
"path": "uploads\\file-1521892130284.png"
},
{
"_id": ObjectId("5ab63b22d012ea2bc0bb7e9c"),
"filename": "file-1521892130285.png",
"path": "uploads\\file-1521892130285.png"
}
]
},
]}
/* we get an array of "files" arrays */
const allFiles = dbResponse.Data.map(x => x.files)
/*
we map a files array to an array of {"small":...}
objects
*/
function getFilenames(files) {
return files.map(keepOnlyFilename);
}
/*
we take an object like:
{
"_id": ObjectId("5ab63b22d012ea2bc0bb7e9d"),
"filename": "file-1521892130284.png",
"path": "uploads\\file-1521892130284.png"
}
and we transform it to:
{
"small": "file-1521892130284.png"
}
*/
function keepOnlyFilename(obj) {
return {
"small": obj.filename
};
}
/* we put the above together as building blocks */
const final = allFiles.map(getFilenames);
console.log(final)
关于javascript - 迭代和转换数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49555045/