0

i'm right now working with a cocktail API and fetch data out of json. My question is:

Is there a way to rename a json key for example it's original is "strIngredient1" and I want it to be just "strIngredient", so that I can count up to the last key with the same name but changing last number. My idea was to include all objects into one string without doing "ingr1" + "ingr2" + "ingr3" and so on:

var x = 1;

var ingr = data.drinks[0].strIngredient+x;

var ListIngr = "";

do{

x++;

ListIngr.innerHTML =+ ${ingr}

while(ingr != null);

I already searched a lot, but couldn't really find anything.I'm still new to working with Json.

JSON of the API

VLAZ
  • 26,331
  • 9
  • 49
  • 67
codeaddy
  • 1
  • 2
  • 1
    (1) Don't post text as image. Type the text (and format with selcet+toolbar button), and (2) provide the desired result for that specific input. (3) read the usage description of the `json` tag -- it doesn't belong here. – trincot Jun 03 '22 at 11:53
  • That console output is showing an object, its properties/keys and its values. Use that to google for an answer, because JSON is a text format and unrelated to your question. (and do not use w3schools to learn JS...) –  Jun 03 '22 at 11:55
  • It's not clear what you wanna do, but you surely can't have two or more keys with the same name in a json file or a JS Object for obvious reasons... If you want to select all keys starting with a certain pattern use a RegExp: `Object.keys(JsonObject).filter(k => /^strIngredient/.test(k))` or something like this. – Cesare Polonara Jun 03 '22 at 12:02
  • Also please state what the actual goal is here. It shouldn't be necessary to mess with the keys, what is the [actual problem](https://xyproblem.info/) you're trying to solve? One way: https://jsfiddle.net/ht53xb2m/ –  Jun 03 '22 at 12:11
  • @ChriG, that's what I was searching for. Sorry for making it that hard to get what I was trying to achieve. – codeaddy Jun 03 '22 at 12:25
  • No problem, the key is that instead of `data.abc + x` you need `data["abc" + x ]` –  Jun 03 '22 at 12:31
  • Duplicate: [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) –  Jun 03 '22 at 12:31

0 Answers0