Javascript Filter Or Reduce Each JSON Object By Child Array Of Tags Which Contains Search Word
I need help regarding filtering below given Javascript Array of Objects by it's sub-child array property. I have one react app in which I want to filter articles when user types s
Solution 1:
You can do this with filter
method in inside check if some
tag includes
part of string that you want to search for.
let articles = [{title: 'title 1', tags :["JavaScript", "ES6"], category: "JavaScript"},{title: 'title 2', tags :["React", "TypeScript"], category: "React"},{title: 'title 3', tags :["JavaScript", "Inheritance", "Prototype"], category: "JavaScript"}]
let search = 'java';
let result = articles.filter(({tags}) => {
return tags.some(e => e.toLowerCase().includes(search.toLowerCase()))
})
console.log(result)
Solution 2:
You can do this with filter
method in inside check if some tag includes part of the string that you want to search for.
let articles = [{title: 'title 1', tags :["JavaScript", "ES6"], category: "JavaScript"},{title: 'title 2', tags :["React", "TypeScript"], category: "React"},{title: 'title 3', tags :["JavaScript", "Inheritance", "Prototype"], category: "JavaScript"}]
let search = "ES";
let result = articles.filter(((data)=>data.tags.some(v => v.includes(search))))
console.log(result)
Solution 3:
I think this is the solution. The fact you had unnescessary elements, is that you only checked if the property children
had a value and was not undefined
. with the check node.children.length > 0
you check if the array has at least 1 item.
// the filter
const nodes = $.grep(data, function f(node) {
const nodeIncludesValue = node.name.toLowerCase().includes(value);
if (node.children && node.children.length > 0) {
return $.grep(node.children, f) || nodeIncludesValue;
}
return nodeIncludesValue;
});
// No unnecessary elements
createTree(nodes, container)
{
const list = document.createElement('ul');
nodes.forEach((node) => {
const listItem = document.createElement('li');
listItem.textContent = node.name;
list.appendChild(listItem);
if (node.children && node.children.length > 0) {
const childList = document.createElement('li');
this.createTree(node.children, childList);
list.appendChild(childList);
}
});
container.appendChild(list);
}
Hopefully this helps you :)
Post a Comment for "Javascript Filter Or Reduce Each JSON Object By Child Array Of Tags Which Contains Search Word"