Home > Software design >  How to access all elements from dictionary - ReactJS
How to access all elements from dictionary - ReactJS

Time:02-06

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: [],              
      }]

KeyValuePair returned from API -> [{"Key":"A","Value":["AQ11"]},{"Key":"B","Value":[]},{"Key":"C","Value":["CN22", "CL33"]}]

I am trying to assign key, value to my parent and child state.

     if (response.ok) {              
                response.json()
                    .then((responseData) => {                           
                        let lengthOfResponse = Object.keys(responseData).length
                   
                        for (var i = 0; i < lengthOfResponse; i  ) {           
                            let items= [...this.state.items];
                            items[i].childItemNo= responseData[i]['Value'][0]; // works finr
                        items[i].parentItemNo= responseData[i]['Key'];                         
                           
                            this.setState({ items});
                        }

But this does not set values to my state. Says undefined.

CodePudding user response:

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"]
  •  Tags:  
  • Related