如何使用.filter
过滤出以下标题?我期望输出类似于:{“ Capuchin Monkey”,“ Capybara”}我正在使用看起来像这样的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"
},
// 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
}
});
答案 0 :(得分:1)
我认为您需要的是地图,而不是过滤器。 像这样:
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);
答案 1 :(得分:0)
要获取诸如{"Capuchin Monkey", "Capybara"}
之类的标题列表,最好使用Array.prototype.map()
而不是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);
答案 2 :(得分:0)
loadCategories(){
let categs = _categories,
trainingCrs = _categories.d.results.map((x) =>x.Courses.results.Title)
});