簡體   English   中英

如何訪問數組中的嵌套對象來驗證它?

[英]How can I access a nested object inside an array to validate it?

這是我的架構:

  detail: [{
         quantity: Number,

         product:{

            name: String,
            code: Number,
            price: Number
          },
          subtotal: Number

       ]}

這是我的驗證方法

  const validations = values => {

     const errors = {

       product: {}

       }

  if(!values.detail || 
      !values.detail.length){

   errors.detail = {_error: 'at 
    least one item must be 
        required'}
   }

    else{

 const detailArrayErrors = []

      values.detail.forEach(   
     (item,itemIndex) =>{

       const detailErrors = {}

     if(!item || !item.quantity){
         detailErrors.quantity 
             ='Required'

    detailArrayErrors[itemIndex]=

        detailErrors 
        }

    if(!item || !item.subtotal){

      detailErrors.subtotal 

        = 'required'


   detailArrayErrors[itemIndex]

         = detailErrors
          }

     //How can I access product
      // in validations method

       })

    if(detailArrayErrors.length)

     errors.detail = 
        detailArrayErrors


    }

      return errors;
          }

    export default validations;

product 是我嵌套的 json 對象的詳細信息。 細節是一個數組。 我想驗證產品。 如何訪問數組中的嵌套 json 對象以對其進行驗證?

我試過使用 for... of,但它沒有結果。

我在網上搜索,但我什么也找不到。

我怎樣才能做到這一點?

有誰知道嗎?

values.detail.forEach(d=> console.log(d.product));

獲取無效數組,例如:

let invalidItems = values.detail.filter(d => !d.product || !d.quantity || 
!d.product.name);

要對數組中的每個項目執行某些操作:

this.values.detail.forEach(i => 
{
 let detailErrors = {'quantity': null, product: null};


if (!i.quantity)
  {
    detailErrors.quantity= 'Required'
  }
 if (!i.product)
  {
   detailErrors.product = 'Required'
  }
if (i.product && !i.product.price)
  {
    detailErrors.product = {'price' :'Required'}
  }

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM