I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.
Any way to do this with map? And present in a list? I've come this far:
const allaOrter = orter.map((allOrt) =>
<li>{allOrt.url}</li>
)
What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how... The real array I'm working with is much bigger and contains loads of urls. Maybe even make new arrays which contains those elements that have a common url. I hope my provided example is enough for someone of you guys to help me out. :)
orter.json
[{
"id": "2",
"namn": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"namn": "Karlshamn",
"url": "/blekinge/karlshamn"
},
{
"id": "24",
"namn": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"namn": "Olofström",
"url": "/blekinge/olofstrom"
},
{
"id": "26",
"namn": "Ronneby",
"url": "/blekinge/ronneby"
}]
CodePudding user response:
Use array.prototype.filter method then map the returned array
const arr = [{
"id": "2",
"namn": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"namn": "Karlshamn",
"url": "/blekinge/karlshamn"
},
{
"id": "24",
"namn": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"namn": "Olofström",
"url": "/blekinge/olofstrom"
},
{
"id": "26",
"namn": "Ronneby",
"url": "/blekinge/ronneby"
}]
let filtered = (a) => a.url.includes("/blekinge")
console.log(arr.filter(filtered))
then map the result
CodePudding user response:
You should first try to narrow down by matching the object which contains the url /blekinge
using the filter
method. Once you have filtered, the resulting array can be used to present a list.
To keep things simple, I implemented an unordered list to present the result, but the core of what you need is in the resulting filtered array.
let listElement = document.getElementById('name-list');
let data = [
{
"id": "2",
"name": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"name": "Karlshamn",
"url": "/blekinge/karlshamn"
},
{
"id": "24",
"name": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"name": "Olofström",
"url": "/blekinge/olofstrom"
},
{
"id": "26",
"name": "Ronneby",
"url": "/test/ronneby"
}
];
let updateList = (list, content) => {
let li = document.createElement("li");
li.innerHTML = content;
list.appendChild(li);
};
let filteredData = data.filter(elem => elem.url.indexOf('/blekinge') !== -1);
filteredData.map(elem => updateList(listElement, elem.name));
<label for="name-list">Matching names</label>
<ul id="name-list">
<ul>