How can i get the name in the picture below?
return testData.then((data) => {
console.log(data)
var results = [];
var toSearch = params.suggestTerm;
data = data["data"]["0"];
console.log("data: ", data["0"])
for(var i=0; i<data.length; i ) {
if(data[i]["name"].indexOf(toSearch)!=-1) {
results.push(data[i]);
}
}
result of console.log(data)
CodePudding user response:
No need to do this :data = data["data"]["0"];
. If you are doing that you are assigning data to be the first object from the nested list. It is not an array anymore.
Just get the list in another variable
and access that:
let list = data.data;
for(var i=0; i<list.length; i ) {
if(list[i]["name"].indexOf(toSearch) !== -1) {
results.push(list[i]);
}
}
The indexOf()
search will be case sensitive. If that is not what you want, you can lowercase and search.
CodePudding user response:
It appears you are looking to have an array only containing items that have name
values in your toSearch
string. If that's the case, you could use Array.filter()
similar to:
return testData.then((data) => {
console.log(data)
var results = [];
var toSearch = params.suggestTerm;
if (data && data.data && data.data.length > 0){
results = data.data.filter(item =>
item.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1
)
return results;
}
This example searches case insensitive. If you wish for a case sensitive search, remove the .toLowerCase()
See Array.filter()