如何过滤数组内的对象数组



我有一个json,里面有"句号"数组内部,我已经有了我想要的方式工作的过滤器代码,但我不能访问json

中的属性jsonthis.transporte

[ { "id": 1, "emp_id": 1, "nome": "Retirada na Loja", "tipo": "RETIRA", "subtipo": null, "latLng": [-25.45264, -49.26653], "vFreteMin": 0, "vFreteGratis": null, "periodos": [ { "id": 8, "transporte_id": 1, "ativo": 1, "periodo": "Comercial (das 8h às 19h)", "corte": "16:00", "data": null, "week": [0, 1, 1, 1, 1, 1, 1] }, { "id": 16, "transporte_id": 1, "ativo": 1, "periodo": "Domingos ou Feriado (Das 9h as 14h)", "corte": "12:00", "data": null, "week": [1, 0, 0, 0, 0, 0, 0] } ] }, { "id": 2, "emp_id": 1, "nome": "Frota Própria", "tipo": "FROTA", "subtipo": null, "latLng": [-25.4522, -49.267], "vFreteMin": 0, "vFreteGratis": 80, "periodos": [ { "id": 4, "transporte_id": 2, "ativo": 1, "periodo": "COMERCIAL (9h as 19h)", "corte": "16:00", "data": "2022-03-24", "week": [0, 1, 1, 1, 1, 1, 1] }, { "id": 17, "transporte_id": 2, "ativo": 1, "periodo": "Domingos ou Feriados (Das 9h as 14h)", "corte": "09:30", "data": null, "week": [1, 0, 0, 0, 0, 0, 0] } ] }, { "id": 20, "emp_id": 1, "nome": "Correios (PAC)", "tipo": "TRANSP", "subtipo": null, "latLng": [-25.4522, -49.267], "vFreteMin": null, "vFreteGratis": null, "periodos": [ { "id": 18, "transporte_id": 20, "ativo": 1, "periodo": "Comercial (Das 8h as 18h)", "corte": "17:30", "data": null, "week": [0, 1, 1, 1, 1, 1, 1] } ] } ]

过滤器

filterPeriodos() {
let object = this.formGeral.value.data;
let jsDate = new Date(object.singleDate?.jsDate);
jsDate.setUTCHours(23,59,59,999);
this.dataFormat=jsDate
const d = new Date(jsDate );
if (this.storeS.layout.emp.id === 1) {
if(this.formGeral.value.entregaBool){
return this.transporte.filter( transpId =>   transpId.periodos.ativo === (1) && transpId.periodos.transporte_id === (this.metodoId) && transpId.periodos.week[d.getDay()] === 1 ) ;
}
}
return this.transporte;
}

this.transporte.filter( transpId =>   transpId.periodos.ativo === (1) && transpId.periodos.transporte_id === (this.metodoId) && transpId.periodos.week[d.getDay()] === 1 ) ;

我无法访问"周期"。数组

在这里,你试图访问数组,没有它的索引,如下所示。

this.transporte.filter( transpId => transpId.periodos.ativo === (1) && transpId.periodos.transporte_id === (this.metodoId) && transpId.periodos.week[d.getDay()] === 1 );

periodos是一个数组,所以要访问它的对象的属性,你需要提供像这样的索引。

this.transporte.filter( transpId => transpId.periodos[index].ativo === (1) && transpId.periodos[index].transporte_id === (this.metodoId) && transpId.periodos[index].week[d.getDay()] === 1 );

注意-这里,索引将根据您的业务需求,可以像0,1,2…n。考虑n是数组的长度/最后一个索引。

希望对你有帮助。

你可以这样写

this.transporte.filter(transpId =>transpId.periodos?.filter((p)=>p.ativo === (1) && p.transporte_id === (this.metodoId) && p.week[d.getDay()] === 1 ));

最新更新