JSON data:
JavaScript
x
2
1
[{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}]
2
I want loop that search for e.g. David’s texts and show it in HTML:
JavaScript
1
3
1
<h1>Hi</h1>
2
<h1>another text</h1>
3
I’m sorry for the bad expression but I don’t know how to explain this.
Advertisement
Answer
HTML Content
JavaScript
1
5
1
<div class="wrapper">
2
3
</div>
4
5
JS Content
JavaScript
1
19
19
1
const list = [
2
{"name": "David", "text": "Hi"},
3
{"name": "Test_user", "text": "test"},
4
{"name": "David","text": "another text"}
5
];
6
7
const searchKey = 'David';
8
9
// filter the objects with name "David" or "david"
10
const searchResult = list.filter(({ name }) => name.toLowerCase() === searchKey.toLowerCase());
11
12
// render the filtered array on HTML
13
const parentWrapper = document.querySelector('.wrapper');
14
searchResult.forEach((el) => {
15
const child = document.createElement('h1');
16
child.textContent = el.text;
17
parentWrapper.appendChild(child);
18
});
19