Skip to content
Advertisement

Get multiply key’value in object that have the same key

JSON data:

[{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}]

I want loop that search for e.g. David’s texts and show it in HTML:

<h1>Hi</h1>
<h1>another text</h1>

I’m sorry for the bad expression but I don’t know how to explain this.

Advertisement

Answer

HTML Content

<div class="wrapper">

</div>

JS Content

const list = [
    {"name": "David", "text": "Hi"},
    {"name": "Test_user", "text": "test"},
    {"name": "David","text": "another text"}
];

const searchKey = 'David';

// filter the objects with name "David" or "david"
const searchResult = list.filter(({ name }) => name.toLowerCase() === searchKey.toLowerCase());

// render the filtered array on HTML
const parentWrapper = document.querySelector('.wrapper');
searchResult.forEach((el) => {
    const child = document.createElement('h1');
    child.textContent = el.text;
    parentWrapper.appendChild(child);
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement