gpt4 book ai didi

javascript - 迭代和转换数组中的对象

转载 作者:搜寻专家 更新时间:2023-10-30 23:30:38 25 4
gpt4 key购买 nike

从数据库中我得到:

"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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com