Reputation: 173
I have a list in this way
let array = [
{ url: 'url1'},
{ url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}],
{ url: 'url3', children: [{url: 'url3/test3/test3}, {url: 'url3/test3/test1'}], children: [{url: 'url3/test3/test1/test5'}]},
{ url: 'url4', children: [{url: 'url4/test4/test4'}, {url: 'url3/test4/test4'}]]
and a input string that is a url.(e.g url: 'url3/test3/test1').
My purpose is to check if input url exist in the list without using for loop.(with map, some, filter or other functions..)
How can I do?
My purpose is to check if the
Upvotes: 0
Views: 90
Reputation: 12629
You can create check
function like below. It will also call itself recursively if children
property exists. Then use some
method to get result.
let array = [{url:'url1'},{url:'url2/test',children:[{url:'url2/test/test'},{url:'url2/test2/test'}]},{url:'url3',children:[{url:'url3/test3/test3'},{url:'url3/test3/test1'}],},{url:'url4',children:[{url:'url4/test4/test4'},{url:'url3/test4/test4'}]}];
function check(arr, url) {
return arr.some(a => a.url == url || (a.children && check(a.children, url)));
}
let isExists = check(array, 'url3/test3/test3');
console.log(isExists);
let isExists2 = check(array, 'url3/test3');
console.log(isExists2);
Upvotes: 2
Reputation: 49
Try this:
var search = "url3/test/test1";
var index = array.indexOf(array.find(el1 => {
if (el1.children != undefined) return el1.children.some(el2 => el2.url.includes(search));
}));
And correct the array, because it's a bit messed up. Snippet:
let array = [
{ url: 'url1'},
{ url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}]},
{ url: 'url3', children: [{url: 'url3/test3/test3'}, {url: 'url3/test3/test1'}, {url: 'url3/test3/test1/test5'}]},
{ url: 'url4', children: [{url: 'url4/test4/test4'}, {url: 'url3/test4/test4'}]}]
function findIt(search) {
var index = array.indexOf(array.find(el1 => {
if (el1.children != undefined) return el1.children.some(el2 => el2.url.includes(search));
}));
if (index > -1) console.log(array[index].url); else console.log("Could not find " + search)
}
<input oninput="findIt(this.value)">
Upvotes: 0