I have an array of objects something like this:
array_ = [
{id: "id_one", name:"name_one"},
{id: "id_two", name:"name_two"},
{
id:"id_three",
data: [
{data:0,name:"name_three"},
{data:0,name:"name_four"}
]
},
{id: "id_four", name: "name_five"}
]
You can see that some are simple objects, but some have an array of sub-objects, but each one has the key name
.
Now, what I want to do is find all the objects with a name
field that includes a string.
For example, if I want to find all the objects with name
values which include the string "name_"
, it should return an array of all the objects in array_
.
But if I test for the string "name_t"
, I'd want it to return an array containing the id:two object and the object with id:three, data[0].
Essentially, a search bar.
But I want it to only search for the beginning of the string. So as above, "name_"
would return all, but "ame_"
would return none.
I don't know if that made any sense, but if It did, I hope someone can help me with this.
Minimal Code:
HTML:
<body>
<input id="text-input" type="text"
</body>
JavaScript (I'm using jQuery):
$('#text-input').on('input', () => {
let inputValue = $('#text-input').val()
function deepSearch (object, key, predicate) {
if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) return object
for (let i = 0; i < Object.keys(object).length; i++) {
if (typeof object[Object.keys(object)[i]] === "object") {
let o = deepSearch(object[Object.keys(object)[i]], key, predicate)
if (o != null) return o
}
}
return null
}
let object_ = deepSearch(array_, "name", (k, v) => v.includes(inputValue))
console.log(object_)
})
This is using a functions I found at this question
This function is almost what I need.
However, it returns the first object with containing the string, whereas I want an array containing all objects that match.