Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP.
This is an example of my json:
{
'username': 'Karl',
'email': '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="542c2d2e143536377a2c2c">[email protected]</a>',
'user_id': 5,
...
}
I have span elements on my page with a data-field attribute. For example:
<span data-field="username">xyz</span>
The json-array is returned from an ajax-request and I want to replace every element where the data-field=""
matches the array-index.
Currently, I am doing this for each element in the json-array:
$("[data-field='username']").text(data.username);
$("[data-field='email']").text(data.email);
But as the number of elements increases, this approach becomes messy. Are there any other alternatives? I've heard about transforming the json into an object, but I'm not sure how to do it.