我有以下JSON文件:http://pastebin.com/1TguvZXc
通过遍历数组,可以在数组中找到重复的“body”:
models[x].years[y].styles[z].submodel.body
换句话说:
models[0].years[0].styles[0].submodel.body
应检查中的重复项:
models[0].years[0].styles[1].submodel.body
models[0].years[0].styles[2].submodel.body
models[0].years[0].styles[n].submodel.body
其余的数据对我来说毫无用处。
我有以下管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterByCategory'
})
export class FilterByCategoryPipe implements PipeTransform {
transform(input: any , search: string): any[] {
if (input === undefined || input.length === 0) {
return input;
}
const filteredArr: Array<any> = JSON.parse(JSON.stringify(input));
for (const model of filteredArr) {
for (const year of model.years) {
year.styles = year.styles.filter(style => {
return style.submodel.body === search;
});
}
}
return filteredArr;
}
}
我如何在我的.filter函数中添加一个额外的'test'来检查'submodel.body'的值是否存在于任何样式数组中?
答案 0 :(得分:2)
基本上,您需要使用filter
函数来删除重复的元素。
因此,删除重复的函数如下所示,并使用indexOf
函数
function removeDuplicate(element, index, array) {
return array.map(style => style.submodel.body).indexOf(element.submodel.body) === index;
}
以下是JS版本的代码,您可以使用它并添加帖子中定义的搜索的where条件。
function removeDuplicate(element, index, array) {
return array.map(style => style.submodel.body).indexOf(element.submodel.body) === index;
}
var data = '{"models":[{"id":"Acura_ILX","name":"ILX","niceName":"ilx","years":[{"id":401640361,"year":2017,"styles":[{"id":401640368,"name":"AcuraWatch Plus Package 4dr Sedan (2.4L 4cyl 8AM)","submodel":{"body":"Sedan","modelName":"ILX Sedan","niceName":"sedan"},"trim":"AcuraWatch Plus Package"},{"id":401640367,"name":"Technology Plus and A-SPEC Packages 4dr Sedan (2.4L 4cyl 8AM)","submodel":{"body":"Sedan","modelName":"ILX Sedan","niceName":"sedan"},"trim":"Technology Plus and A-SPEC Packages"},{"id":401640366,"name":"Premium Package 4dr Sedan (2.4L 4cyl 8AM)","submodel":{"body":"Sedan","modelName":"ILX Sedan","niceName":"sedan"},"trim":"Premium Package"},{"id":401640365,"name":"Premium and A-SPEC Packages 4dr Sedan (2.4L 4cyl 8AM)","submodel":{"body":"Sedan","modelName":"ILX Sedan","niceName":"sedan"},"trim":"Premium and A-SPEC Packages"},{"id":401640364,"name":"Technology Plus Package 4dr Sedan (2.4L 4cyl 8AM)","submodel":{"body":"Sedan","modelName":"ILX Sedan","niceName":"sedan"},"trim":"Technology Plus Package"},{"id":401640363,"name":"4dr Sedan (2.4L 4cyl 8AM)","submodel":{"body":"Sedan","modelName":"ILX Sedan","niceName":"sedan"},"trim":"Base"}]}]},{"id":"Acura_NSX","name":"NSX","niceName":"nsx","years":[{"id":200779937,"year":2017,"styles":[{"id":101418796,"name":"2dr Coupe AWD (3.5L 6cyl Turbo gas/electric hybrid 9AM)","submodel":{"body":"Coupe","modelName":"NSX Coupe","niceName":"coupe"},"trim":"Base"}]}]}],"modelsCount":6}';
var jsonData = JSON.parse(data);
jsonData.models.forEach(model =>
model.years.forEach(year =>
year.styles = year.styles.filter(removeDuplicate)
));
console.log(jsonData);