My asp.net core Web API returns Id and Names like this:
[HttpGet("{id}/names")]
public async Task<IEnumerable<VisaNameDto>> GetVisaNames(string id)
{
visaNames = await visaDtoRepo.GetVisaNames(id);
return visaNames;
}
public class VisaNameDto
{
public int Id { get; set; }
public string Name { get; set; }
}
When I consume this API and console log on the client I get the output as:
const uri = "https://localhost:44395/visa/ae/names";
fetch(uri)
.then((response) => response.json())
.then((data) => console.log(data));
------------------------------------------------------------
{$id: '1', $values: Array(7)}
$id: "1"
$values: Array(7)
0: {$id: '2', id: 1, name: '48 Hours Transit Visa'}
1: {$id: '3', id: 2, name: '30 Days Tourist Visa'}
2: {$id: '4', id: 3, name: '30 Days Multiple Entry Tourist Visa '}
3: {$id: '5', id: 4, name: '96 Hours Transit Visa'}
4: {$id: '6', id: 5, name: '14 Days Tourist Visa '}
5: {$id: '7', id: 6, name: '14 Days Tourist Visa (Express)'}
6: {$id: '8', id: 7, name: '30 Days Tourist Visa (Express)'}
length: 7
[[Prototype]]: Array(0)
[[Prototype]]: Object
How can I loop through this in JavaScript and access the Id and Name? I am not even getting the length of this (data.length shows undefined). Also where does the $id comes from?
The response is an object with properties $id and $values.
const uri = "https://localhost:44395/visa/ae/names";
fetch(uri)
.then((response) => response.json())
.then(data => {
data.$values.forEach(value => {
// do something with value, eg.
console.log(value.$id, value.id, value.name)
})
});