PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] 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

 October 13, 2022     axios, javascript, object     No comments   

Issue

New using Axios. I need help with the body formatting of my Axios post in React Js

My code:

  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,
      },
    }))
  )

At the moment it is printing the data, as it maps each product like this:

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'
    }
  }
]

However, I would like the format to be such that the timestamp and number of products are printed once and then maps through all selected products. Like this below:

    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' }
 }
}

Solution

To get close to what you want, you would simply do this

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,
    })),
})

Hope that helps

edit: oops, typo



Answered By - Jaromanda X
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing