从数据库中我得到:
"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。
答案 0 :(得分:1)
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)

答案 1 :(得分:0)
首先使用var Data = JSON.parse(str);
然后,创建一个新对象var galleryImage = [];
并迭代数据数组。
for(var i =0; i < Data.files.length; i++)
galleryImages[i] = { small : Data.files[i].filename }
答案 2 :(得分:0)
对于所有文件名的数组,您需要迭代Data
和files
的内部数组。然后构建新对象并通过减少外部数组来映射内部结果。
使用的方法:
Array#reduce
表示外部数组,数组为start vlaue,
用于获取对象的单个属性的destructuring assignment
Array#concat
用于合并两个数组
Array#map
用于获取具有所需重命名属性的新对象
function ObjectId(v) { return v; }
var $scope = { "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" }] }] },
array = $scope.Data.reduce(
(r, { files }) => r.concat(files.map(({ filename: short }) => ({ short }))),
[]
);
console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;