[英]how can i transform this object in to array?
Hi I have this object and I want to loop over this object with a forEach but I can't, how can I transform it into an array?嗨,我有这个对象,我想用 forEach 循环这个对象,但我不能,我怎样才能把它转换成一个数组? Sorry for my ignorance but is this a json object?
抱歉我的无知,但这是一个 json 对象吗?
{
file0: {
fieldName: 'file0',
originalFilename: '4.png',
},
file1: {
fieldName: 'file1',
originalFilename: '1.jpg',
},
file2: {
fieldName: 'file2',
originalFilename: '2.jpg',
},
file3: {
fieldName: 'file3',
originalFilename: '3.png',
}
}
The array would be something like this:该数组将是这样的:
[
{},
{},
{},
{}
]
Which one of these do you need?您需要其中的哪一种?
The one with just the objects or one with objects AND key?一个只有对象还是一个对象和键?
const obj = { file0: { fieldName: 'file0', originalFilename: '4.png', }, file1: { fieldName: 'file1', originalFilename: '1.jpg', }, file2: { fieldName: 'file2', originalFilename: '2.jpg', }, file3: { fieldName: 'file3', originalFilename: '3.png', } } // fast const arr1 = Object.values(obj).slice(0); // see below why I slice console.log(arr1); // alternative using map: const arr2 = Object.keys(obj).map(key => obj[key]); console.log(arr2); // include the key: const arr3 = Object.keys(obj).map(key => ({ [key]: obj[key] })); console.log(arr3); // Taking the Object.values directly, will POINT to the original object: const arr4 = Object.values(obj); arr4[0].fieldName = "XXX" console.log(obj);
You can simply use map()
and get the desired result as below:您可以简单地使用
map()
并获得如下所需的结果:
const obj = {
file0: {
fieldName: 'file0',
originalFilename: '4.png',
},
file1: {
fieldName: 'file1',
originalFilename: '1.jpg',
},
file2: {
fieldName: 'file2',
originalFilename: '2.jpg',
},
file3: {
fieldName: 'file3',
originalFilename: '3.png',
}
}
const arr = Object.keys(obj).map(key => obj[key])
and get the following result:并得到以下结果:
[
{fieldName: "file0", originalFilename: "4.png"},
{fieldName: "file1", originalFilename: "1.jpg"},
{fieldName: "file2", originalFilename: "2.jpg"},
{fieldName: "file3", originalFilename: "3.png"}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.