簡體   English   中英

How I get the javascript object I want from the javascript object I have and pass that to a nested (complex) body using Axios to post an API

[英]How I get the javascript object I want from the javascript object I have and pass that to a nested (complex) body using Axios to post an API

新使用 Axios。 我在 React Js 中的 Axios 帖子的正文格式方面需要幫助

我的代碼:

  body: JSON.stringify(
    {
      quote_timestamp: timestamp,
      number_of_products: state.length,
    } &&
    state.map((product) => ({
      quote_timestamp: timestamp,
      number_of_products: state.length,
      products: {
        cat_Number: product.cat,
        product_Name: product.Name,
      },
    }))
  )

目前它正在打印數據,因為它像這樣映射每個產品:

body [
  {
    quote_timestamp: '7/24/2022, 11:25:27 PM',
    number_of_products: 3,
    products: {
      cat: 'AB1',
      Name: 'Alpha'
    }
  },
  {
    quote_timestamp: '7/24/2022, 11:25:27 PM',
    number_of_products: 3,
    products: {
      cat: 'AB2',
      Name: 'Beta'
    }
  },
  {
    quote_timestamp: '7/24/2022, 11:25:27 PM',
    number_of_products: 3,
    products: {
      cat: 'AB3',
      Name: 'Gamma'
    }
  }
]

但是,我希望格式是這樣的,即時間戳和產品數量打印一次,然后映射到所有選定的產品。 像下面這樣:

    body[ {
        quote_timestamp: '7/24/2022, 11:25:27 PM',
        number_of_products: 3,
        products: { 

    { cat: 'AB1', Name:'Alpha' }, 
    
    { cat: 'AB2' Name:'Beta' }.
    
    { cat: 'AB3' Name:'Gamma' }
 }
}

為了接近你想要的,你只需這樣做

JSON.stringify({
    quote_timestamp: timestamp,
    number_of_products: state.length,
    total_price: total,
    products: state.map((product) => ({
        cat_Number: product.Cat_Number,
        product_Name: product.Product_Name,
        Price: product.mockPrice,
    })),
})

希望有幫助

編輯:哎呀,錯字

暫無
暫無

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

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