考虑此数组:
const body = [
{id: 1,courses: [{title:"course1.1", results:[]}, {title:"course1.2", results:[]}]},
{id: 2,courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]},
];
我正在尝试获得第一条没有任何结果的课程的身体。
我尝试过:
body.filter(session=>session.courses.filter(course=>course.results.length<=0));
但是出于某种原因,我不理解它会返回所有项目。
任何帮助将不胜感激,谢谢!
P.S。我已经尝试使用Array.some和简单的forEach了,没有运气。
编辑:我忘了包括我的jsfiddle测试https://jsfiddle.net/jonathanlaf/4os0fzv1/
Edit2:我知道过滤器将返回所有匹配的结果,这很好,我可以获取新返回的数组的第一个索引。
Edit3:我实际上希望新返回的数组如下所示:
const body2 = [
{id: 2,courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]},
];
答案 0 :(得分:3)
这应该做到:
const body = [ {id: 1,courses: [{title:"course1.1", results:[{title:"result1.1.1"}, {title:"result1.1.2"}]}, {title:"course1.2", results:[]}]}, {id: 2,courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]}, {id: 3,courses: []}];
console.log(body.reduce((r,c) => (c.courses.length ? r.push({ id: c.id, courses: [...c.courses.filter(({results}) => !results.length)]}) : true) && r, []))
更新:在courses
只是一个没有结果的空数组的情况下增加了处理,例如{id: 3,courses: []}
。
答案 1 :(得分:1)
您可以映射新对象而无需更改原始数据。
var array = [{ id: 1, courses: [{ title: "course1.1", results: [{ title: "result1.1.1" }, { title: "result1.1.2" }] }, { title: "course1.2", results: [] }] }, { id: 2, courses: [{ title: "course1.1", results: [] }, { title: "course1.2", results: [] }] }],
result = array.map(o =>
Object.assign(
{},
o,
{ courses: o.courses.filter(({ results: { length } }) => !length) }
)
);
console.log(result);
答案 2 :(得分:-1)
const body = [
{id: 1,courses: [{title:"course1.1", results:[{title:"result1.1.1"}, {title:"result1.1.2"}]}, {title:"course1.2", results:[]}]},
{id: 2,courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]},
];
let results = body.find(session => -1 < session.courses.findIndex(course => course.results.length <=0))
console.log(results)