How would I filter out the following Titles using .filter
? I'm expecting the output to be something like: {"Capuchin Monkey", "Capybara"} I'm working with JSON that looks like this:
{
"d": {
"results": [
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Courses": {
"results": [
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Title": "Capuchin Monkey"
},
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Title": "Capybara"
},
// Courses/Title is what I'm interested in
axios.get([redacted] + "/getByTitle('Categories')/items?$select=Title,Description,Courses/Title,SortOrder&$expand=Courses&$orderby=Title&$top=1000",
{
method: "GET",
credentials: "include",
mode: "no-cors",
headers: {
"Accept": "application/json; odata=verbose"
}
}),
// irrelevant code
]).then(axios.spread((cat, lib, admn) => {
_categories = cat.data.d.results; // -------- //
this.loadCategories();
})).catch(error => {
console.log(error);
});
getCategories(){
return _categories;
}
loadCategories(){
let categs = _categories,
trainingCrs = _categories.d.results.filter(x => {
return {
"crsTitle": x.Courses.results.Title // code smell
}
});
I think you need is map, not filter. Something like this:
var json = { "results": [ { "__metadata": { "id": "N/A", "type": "N/A" }, "Courses": { "results": [ { "__metadata": { "id": "N/A", "type": "N/A" }, "Title": "Capuchin Monkey" }, { "__metadata": { "id": "N/A", "type": "N/A" }, "Title": "Capybara" }]}}]}; const reducedResult = json.results.reduce((act, val)=> act.concat(val)); const titles = reducedResult.Courses.results.map((value)=>value.Title); console.log(titles);
To get a list of Titles such as {"Capuchin Monkey", "Capybara"}
, you better use Array.prototype.map() rather than Array.prototype.filter() .
var json = { "d": { "results": [ { "__metadata": { "id": "N/A", "type": "N/A" }, "Courses": { "results": [ { "__metadata": { "id": "N/A", "type" : "N/A" }, "Title": "Capuchin Monkey" }, { "__metadata": { "id": "N/A", "type": "N/A" }, "Title": "Capybara" } ] } } ] } } // Use of .map trainingCrs = json.d.results[0].Courses.results.map(x => x.Title); console.log("Training title list: ", trainingCrs); // Use of .filter trainingCrs = json.d.results[0].Courses.results.filter(x => x.Title === "Capybara"); console.log("Training list filter on one Title", trainingCrs);
loadCategories(){
let categs = _categories,
trainingCrs = _categories.d.results.map((x) =>x.Courses.results.Title)
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.