skip to Main Content

I have the following code which I restructured for simplicity and re-usability. My requirement is simple: I have a list of empty arrays which are mapped to certain keys (corresponding to a set of unique ID’s).

In order to store data into these n number of arrays, I have a common API call whose request payload would contain the id of the reference data, and then on receiving the response I wish to look up the name of the variable inside the object, corresponding to the ID and store the value there before proceeding to next iteration value/ID

example: if value of id is 1, the request payload will have id as one, and the corresponding response data should be saved into the value of mapped[1] ie. fruits… (the array named "fruits" given above, and not the object value, how do I do that?)

let fruits=[]
let vegetables=[]
let nuts=[] ......etc upto n number of entries

let mapped={1:fruits,2:vegetables,3:nuts,.......(other 'n' entries) }

for(let i=1;i<=15;i++){
    let payload={id:i}
   this.apiService.fetchReferenceData(payload).then((response)=>{
         mapped[i]=response.data  //the value I receive here needs to be stored into the array matching the name of the object value
    })

  }
}

2

Answers


  1. You can use an array method like push to store the value inside the array.

    So instead of using – mapped[i]=response.data, use can use mapped[i].push(response.data)

    P.S: Based on the code you provided I am assuming that you are storing the reference of each array(fruits, vegetables, and so on) inside the mapped object.

    Login or Signup to reply.
  2. Jay Swamianrayan!

    Everything else looks fine… Perhaps what you are looking for is…

    mapped[i].push(response.data)
    

    instead of

    mapped[i]=response.data
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search