0

The problem is in the title. Context: I have an API that I access with Fetch.

fetch(apiUrl)
    .then( (data) => {
        if(data.ok){
            return data.json()
        }
        throw new Error('Response not ok.'); 
    })
    .then( player => generateHtml(player))
    .catch( error => console.error('Error:', error))

But I want to display the content of the API in the HTML file. I solved it like this.

const generateHtml = (data) => {
    console.log(data)
    const html = `
        <h2 class="" >${data.profiles.028304b866cc47d18c08e902edfcb4c6.data.display_name}</h2>
        <div class="name">${data.profiles.028304b866cc47d18c08e902edfcb4c6.cute_name}</div>
        <div class="armor">${data.profiles.028304b866cc47d18c08e902edfcb4c6.items.armor_set}</div>
        <div>Rarity: ${data.profiles.028304b866cc47d18c08e902edfcb4c6.items.armor_set_rarity}</div>
    `
    const playerprofilebox = document.querySelector('#object')
    playerprofilebox.innerHTML = html

But as you can see, the element after profiles starts with a number but I can't remove the number because then the API would no longer access the correct data. Any suggestions?

  • I didn't quite understand... How should I insert this into the code so that it works? I mean the path is not changeable as mentioned above because otherwise the correct target is not addressed. – Schleimfresse Nov 10 '21 at 17:09
  • The [highest voted answer](https://stackoverflow.com/a/12953750/215552) has a [link to documentation on bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators#Bracket_notation) that explains exactly that. But basically, instead of `data.profiles.028304b866cc47d18c08e902edfcb4c6.data.display_name` you would have `data.profiles['028304b866cc47d18c08e902edfcb4c6'].data.display_name`. – Heretic Monkey Nov 10 '21 at 17:12
  • Thx finally I have understood it. – Schleimfresse Nov 10 '21 at 17:14

1 Answers1

0

Because it starts with a number, you need to access it with bracket notation:

var obj = {
    '0123abc': 10,
    '4567def': 20
};
console.log(obj['0123abc']); // 10
console.log(obj.0123abc); //SyntaxError
``
2pichar
  • 1,348
  • 4
  • 17