1

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!

5
  • 1
    Try using a different variable name besides 'array'. Commented Apr 8, 2020 at 9:31
  • Just tried but it doesn't change Commented Apr 8, 2020 at 9:33
  • Is this your entire code? I see no reason why array would be undefined. Commented Apr 8, 2020 at 9:39
  • Try use method Array.from() to covert object to array. Here is the documentation: developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/… Commented Apr 8, 2020 at 9:39
  • No that's not my entire code; I fixed anyway the issue following Dennis Vash's answer. Thanks everyone for trying help though! Commented Apr 8, 2020 at 9:49

1 Answer 1

1

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));

Sign up to request clarification or add additional context in comments.

2 Comments

Tried it and it actually works, thanks a lot!! For avoiding future issues like this one, do you know why I was getting an undefined value with the previous code?
Can't find a mistake on those snippets, it should come from some other place

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.