将每个循环中的先前值与当前值进行比较

时间:2017-01-23 15:32:25

标签: express pug

我有一个json,我必须在我的玉中迭代:

[

{ RefSlipNo: 
   { fieldlabel: 'RefSlipNo',
     fieldname: 'RefSlipNo',
     fieldtype: 'text',
     required: '1',
     default_value: '',
     placeholder: 'Ref Slip No',
     order_no: '1',
     formgroup: 'vehicleDetails',
     can_delete: '0',
     status: '1' },
  BookNumber: 
   { fieldlabel: 'BookNumber',
     fieldname: 'BookNumber',
     fieldtype: 'text',
     required: '1',
     default_value: '',
     placeholder: 'Book Number',
     order_no: '2',
     formgroup: 'vehicleDetails',
     can_delete: '1',
     status: '1' },
  SlipDate: 
   { fieldlabel: 'SlipDate',
     fieldname: 'SlipDate',
     fieldtype: 'text',
     required: '1',
     default_value: '',
     placeholder: 'Slip Date',
     order_no: '3',
     formgroup: 'invoice',
     can_delete: '1',
     status: '1' },
  FillFuelDate: 
   { fieldlabel: 'FillFuelDate',
     fieldname: 'FillFuelDate',
     fieldtype: 'text',
     required: '1',
     default_value: '',
     placeholder: 'Fill Fuel Date',
     order_no: '4',
     formgroup: 'invoice',
     can_delete: '1',
     status: '1' }
]

我想在formgroup的基础上使用fieldset和legend:

-------invoice--------------------|
FillFuelDate :                    |
SlipDate :                        |
----------------------------------|

-------vehicleDetails-------------|
RefSlipNo :                       |
BookNumber :                      |
----------------------------------|

但无法获得逻辑。如何在玉中循环它。我希望获得所有字段列表,其中发票表格组在一个字段集下,所有车辆详细信息都在1字段集下,如上所示。

1 个答案:

答案 0 :(得分:0)

在JavaScript中,定义一个这样的函数,并将其作为局部传递给您的pug模板:

function groupByFormGroup(fields) {
  const formGroups = [];
  const formGroupsByName = {};
  fields.forEach(field => {
    if (!formGroupsByName[field.formGroup]) {
      formGroupsByName[field.formGroup] = {name: field.formGroup, fields: []};
      formGroups.push(formGroupsByName);
    }
    formGroupsByName[field.formGroup].push(field);
  });
}

然后在pug模板中,执行以下操作:

each formGroup in groupByFormGroup(fields)
  fieldset
    legend= formGroup.name
    each field in formGroup.fields
      label= field.fieldLabel
      input(type="text" name=field.fieldName)