Search code examples
reactjsdictionaryreact-class-based-component

How to access all elements from dictionary - ReactJS


API returns parents and their children in a dictionary.

// Dictionary with string as its key(parent) and list of strings(children) as its value as below:

        { "A": ["AQ11"], "B": [], "C": ["CN22", "CL33"] }

I have two questions, Have I set my data structure correct to hold the API values (does it add all parents and children to dictionary).

And how do I iterate thru all elements in the dictionary. Thanks.

Below is my state:

    this.state = {
      items:
          {
                parentItemNo: "",
                childItemNo: [],              
          }
  return (
        <div>                      
            {this.state.items.parentItemNo},
            {this.state.items.childItemNo[1]}
        </div>
     )

Above returns only the last element of the dictionary -> C, CL33.

I have changed my data structure now as below as advised.

items:
      [{
            parentItemNo: "",
            childItemNo: [],              
      }]

Solution

  • I think the problem here is that you are saving an object that has repeated keys. The key 'parentItemNo' is being saved with 3 different values and the first values are being overriden with the latest values. You should (if it's within your possibilities) save an array of objects like this:

    items: [
        { parentItemNo: "A", childItemNo: ["AQ11"] },
        { parentItemNo: "B", childItemNo: [] },
        { parentItemNo: "C", childItemNo: ["CN22", "CL33"] }
    ]
    

    and then you can access the different objects (or dictionaries) like this:

        items[0].parentItemNo //returns "A"
        items[2].childItemNo //return ["CN22", "CL33"]