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? Sorry for my ignorance but is this a json object?
{
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments