I have a string text after fetching an API with a for loop, that returns me a list of names, each name separated by a new line. When I use the code in the snippet, it returns me each name in an individual array, instead of a single array. Is there anything wrong with the RegEx? Could someone please tell me what is wrong? Thank you very much for the help.
JavaScript
x
15
15
1
function loadMagicItems() {
2
fetch('https://api.open5e.com/magicitems/?fields=slug,name,desc,type,rarity&limit=1000'
3
).then(function (responses) {
4
return responses.json();
5
}).then(function (data) {
6
displayMagicItems(data);
7
});
8
};
9
10
function displayMagicItems(data) {
11
for (let i = 0; i < data.results.length; i++) {
12
const magicItemsName = data.results[i].name.split(/n/);
13
console.log(magicItemsName);
14
};
15
};
JavaScript
1
2
1
<body onload="loadMagicItems()">
2
</body>
Advertisement
Answer
Your JSON data is an array of items. Not all items as one string seperated by a newline character.
The easiest way to get the names of the items, is to use a map
and return the name of the item.
JavaScript
1
12
12
1
function loadMagicItems() {
2
fetch('https://api.open5e.com/magicitems/?fields=slug,name,desc,type,rarity&limit=1000').then(function(responses) {
3
return responses.json();
4
}).then(function(data) {
5
displayMagicItems(data.results);
6
});
7
};
8
9
function displayMagicItems(items) {
10
items = items.map(({name}) => name);
11
console.log(items);
12
};
JavaScript
1
1
1
<body onload="loadMagicItems()" />