这是我尝试转换为数组的对象:
{ 1: {..}, 2: {..}, 3: {..}, 4: {..}, 5: {..}}
这是我用来将对象转换为数组的函数:
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 [];
}
}
这里是渲染方法:
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>
);
}
};
这里的问题是我收到“无法读取未定义的属性‘映射’”的错误,当在控制台内我记录了带有值的数组时 - 所以我不明白如何获取未定义的值
These are the objects/arrays I get logged into console 我尝试过以下其他问题: 1.Object to Array returns undefined 2.Mapping Object to convert object to array
但是它们的用处不足以解决这个问题
预先感谢您的建议!
最佳答案
尝试使用Object.values
返回对象值的数组。
const object = { 1: { a: 'a'}, 2: { b: 'b'}, 3: { c: 'c'} }
const convertObjectToArray = Object.values;
console.log(convertObjectToArray(object));
关于javascript - 将对象转换为数组返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61097421/