Reputation: 75
I need to create a loop to search into some results to find a path and push it into an array but the way I wrote the loop, it searches only the first position, the [0].
How do I loop all of results positions in order to extract the path from all of them?
For better understanding, please check the image and the code below:
The code so far looks like:
let results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
//loop on each results
results[0].Cells.results.forEach(el => {
let filePath = el.value;
let fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length);
// push to array
pathResults.push(fileName);
});
Thanks in advance for any suggestions!
Upvotes: 0
Views: 299
Reputation: 13431
const pathList = data
.d.query
.PrimaryQueryResult
.RelevantResults
.Table.Rows
.results
.reduce((list, { Cells }) => {
const cellPathItem = Cells
.results.find(({ Key }) => Key === 'Path');
if (cellPathItem) {
list.push(
cellPathItem.Value.substring(
cellPathItem.Value.lastIndexOf('/')
)
);
}
return list;
}, []);
"Thanks for your sophisticated solution! Could you please show me an approach based more on my existing code?"
const pathList = [];
data.d.query
.PrimaryQueryResult
.RelevantResults
.Table.Rows
.results
.forEach(rowItem => {
const cellPathItem = rowItem.Cells
.results.find(cellItem => cellItem.Key === 'Path');
if (cellPathItem) {
pathList.push(
cellPathItem.Value.substring(
cellPathItem.Value.lastIndexOf('/')
)
);
}
});
Upvotes: 1