[英]How to add items in already declared array of object in javascript
I want to add new items from array to an object我想将数组中的新项目添加到 object
here is my object这是我的 object
var newCourse = {
title,
categoryId,
price,
userId,
images: [{ }] };
i am getting data from req.files我正在从 req.files 获取数据
[
{
fieldname: 'file',
originalname: '312323.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './public/uploads',
filename: 'file-1596169590513.jpg',
path: 'public\\uploads\\file-1596169590513.jpg',
size: 536245
},
{
fieldname: 'file',
originalname: 'Capture.PNG',
encoding: '7bit',
mimetype: 'image/png',
destination: './public/uploads',
filename: 'file-1596169590520.PNG',
path: 'public\\uploads\\file-1596169590520.PNG',
size: 13572
}
]
i want to add req.files.filename (which are two) to that object so it can look like this:我想将 req.files.filename (这是两个)添加到 object 所以它看起来像这样:
title: abc,
images:[{url: 'file-1596169590513.jpg'}, {url: 'file-1596169590520.PNG'}]
var newCourse = { title: '', categoryId: '', price: 0, userId: '', images: [] }; var req = { files: [ { fieldname: 'file', originalname: '312323.jpg', encoding: '7bit', mimetype: 'image/jpeg', destination: './public/uploads', filename: 'file-1596169590513.jpg', path: 'public\\uploads\\file-1596169590513.jpg', size: 536245 }, { fieldname: 'file', originalname: 'Capture.PNG', encoding: '7bit', mimetype: 'image/png', destination: './public/uploads', filename: 'file-1596169590520.PNG', path: 'public\\uploads\\file-1596169590520.PNG', size: 13572 } ] }; newCourse.images.push(...req.files.map((file) => { return {url: file.filename}; })); console.log(newCourse);
First you have to map on req.files
to get the file name array as below:首先,您必须在 req.files 上
req.files
以获取文件名数组,如下所示:
const req = {files: []};
const reqImages = req.files.map((file) => { url: file.filename });
Now, assign this reqImages
to images
of your newCourse
variable:现在,将此
reqImages
分配给newCourse
变量的images
:
newCourse.images = reqImages;
Try this尝试这个
let obj = {}; let images = []; for(i = 0; i < arr.length; i++){ obj.url = arr[i].filename; images.push(obj); } console.log(images);
use something like this:使用这样的东西:
for (let item of req.files)
newCourse.images.push({ url: item.filename });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.