0

First of all, I am very new to React, so please excuse my ignorance. But I am really struggling to get a piece of code to work.

First of all, the premise is that I have an array of class objects, and I am trying to incorporate them into a dictionary, where the key is a text property from that class object, and the value is an array of those objects with the property matching that key.

The idea is so that when I render the page, I can group all of those objects based on the key value.

Hopefully, this will make sense in my illustration below.

Assume that I have a class, as follows:

export class MyClass {
  type: string;
  description: string;
  // other class properties
}

And my react component receives a list of those objects:

export interface IMyComponentProps {
  myClasses?: MyClass[];
}

export const MyComponent: FC<IMyComponentProps > = ({myClasses}) => {
 ...
}

The idea is that I want to end up with a dictionary, with each key as a unique 'type' value from each class in that list, and the value is the list of classes that have that particular type.

I have spent a long while trying to get it to work, with the code below the closest I have managed. However, it falls over when trying to render the page, with a generic error.

export const MyComponent: FC<IMyComponentProps > = ({myClasses}) => {
  const myDictionary: {
    [key: string]: MyClass[]
  } = {};

  const populateDictionary = (myClasses: MyClass[]) => {
    myClasses.forEach(populateDictionaryItem);
  };

  const populateDictionaryItem(myClass: MyClass)
  {
    myDictionary[myClass.type].push(myClass);
  }

  useEffect(() => {
    populateDictionary(myClasses);
  }, [myClasses]);
  
  return (
    <div>
     ...
    </div>
  )
}

Based on what I have read and how Javascript handles arrays, that should work, but it doesn't, and I am wondering if anyone is able to see what I am doing incorrectly.

Could it be that I have to inspect the dictionary first to see if the key exists, and create an empty array before the push if it doesn't? I haven't managed to work out the syntax to achieve that.

Again, apologies for my lack of experience, there are probably a few things in the code above that I am not doing correctly.

1 Answer 1

0

OK, I now have it working.

The issue was, as I suspected, that I needed to instantiate an empty array first. After some experimentation, I did it like this:

const populateDictionaryItem(myClass: MyClass)
{
  if (myDictionary[myClass.type] == null)
  {
    myDictionary[myClass.type] = [];
  }
  myDictionary[myClass.type].push(myClass);
}

Thanks

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

Comments

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.