0

I'm looping over an array, getting data from an API on each iteration.

I want to pass data from all iterations of the loop from my express server to the browser using res.json(), so I want to create an object that contains an object of data for each API call, as well as some other key-value pairs that will be created depending on what is returned.

e.g.
on loop index 0:

artist0: 
     {
        data: 'data',
        moreData: 'more-data'
     }

on loop index 1:

artist1: 
     {
        data: 'data',
        moreData: 'more-data'
     }

etc

I would use an array, but one of the calls (at random) will result in another key value pair, e.g.:

correctAnswer: 'a_url.com' 

this will be generated by one of the earlier API calls at random, so I cant get it at the other end using its array index.

I need the key 'correctAnswer', so I also need each object of API data to be identified by which API call it came from.

Short question: Can I name keys based on variables?

As always, your kind help is greatly appreciated :-)

mousetail
  • 7,009
  • 4
  • 25
  • 45
PaulH
  • 29
  • 1
  • 7
  • Why? JSON can encode arrays just fine, just send the data as an array with correctly indexed elements, then unpack it browser-side to work with? – Mike 'Pomax' Kamermans Mar 01 '22 at 17:52
  • 2
    Yes, keys can be created however you want, using either `{ [someExpression]: someValue }` or by `anObject[someExpression] = someValue`. – Dave Newton Mar 01 '22 at 17:55

1 Answers1

0

You could solve this by not putting artists directly in the object, like this, using a array inside a single attribute of the object:

{
    "artists": [
        {
            "data": "data",
            "moreData": "more-data"
        },
        {
            "data": "data",
            "moreData": "more-data"
        }
    ],
    "correctAnswer": 3
}

Or alternatively, if you really want a dynamic key you can use

{
     [`artist${artistIndex}`]: {'data': 'data'}
}
mousetail
  • 7,009
  • 4
  • 25
  • 45