Reputation: 1768
Here is the object I'm trying to convert into array:
{ 1: {..}, 2: {..}, 3: {..}, 4: {..}, 5: {..}}
This is the function I'm using to convert the Object into array:
const convertObjectToArray = (object) => {
const array = [];
if (object) {
Object.keys(object).forEach((key) => {
array.push({[key]: object[key]});
})
console.log('object inside function', object);
console.log('array inside function', array);
return array;
} else {
return [];
}
}
And here the render method:
class PostList extends React.Component {
render() {
const { postList } = this.props;
const array = convertObjectToArray(postList);
console.log('postList', postList);
console.log('array', array);
return (
<div>
{array.map(({ id, ...otherCollectionProps }) => {
return (
<Post key={id} {...otherCollectionProps} />
);
})}
</div>
);
}
};
The problem here is that I get the error of "Cannot read property 'map' of undefined", when inside the console I get logged the array with values - and so I don't understand how I get the undefined value
These are the objects/arrays I get logged into console I have tried following these other issues: 1. Object to Array returns undefined 2. Mapping Object to convert object to array
But they were not useful enough to get this issue fixed
Thanks in advance for your suggestions!
Upvotes: 1
Views: 730
Reputation: 53984
Try using Object.values
which returns an array of object's values.
const object = { 1: { a: 'a'}, 2: { b: 'b'}, 3: { c: 'c'} }
const convertObjectToArray = Object.values;
console.log(convertObjectToArray(object));
Upvotes: 1