Home > Net >  How to access certain element of nested objects in react
How to access certain element of nested objects in react

Time:09-03

I'm struggling to take certain value out of an API. I have no trouble mapping over the parts that I can immediately access using items.value, but when I can't get some of the more nested info. I'm specifically trying to access the value of "quantity" inside of pricing. Here's my code

import "./StoreDisplay.css"


    class StoreDisplay extends Component {
    constructor(props) {
  super(props)

  this.state = {
     error: undefined,
     isLoaded: false,
     items: []

  }
}


componentDidMount() {
    this.getData();
  }

  getData() {
    fetch(url)
    .then((res) => res.json())
    .then(
      (result) => {
        this.setState({
          isLoaded: true,
          items: result,

        });
        console.log(result)
      },
      (error) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    );
 }



     render() {

      const { error, isLoaded, items } = this.state;
      if (error) {
        return <div>Error: {error.message}</div>;
      } else if (!isLoaded) {
        return <div>Loading...</div>;
      } else {
        return (
          <div id = "storeDisplay">
            <ul className = "container">
              {items.map(item => (
                <li key = {item.title}>
                  <div className = "bundleName"> {item.title} {item.pricing.quantity}</div><img src = {item.asset} className = "img"></img>
                </li>
              ))}
            </ul>
          </div>
        );
      }
    }
  }

Sample part of JSON from API:

 [
    {
        "title": "100-Pack Bundle",
        "desc": "",
        "tag": "",
        "purchaseLimit": 1,
        "isAvailable": true,
        "expireTimestamp": 1662538288,
        "shopType": "specials",
        "originalPrice": 10500,
        "pricing": [
            {
                "ref": "Apex Coins",
                "quantity": 6700
            }
        ],
        "content": [
            {
                "ref": "weapon_charm_charm_apex_asset_v22_misc_pathfinderemoji01",
                "name": "MRVN Monitor",
                "quantity": 1
            },
            {
                "ref": "pack_cosmetic_rare",
                "name": "Apex Pack",
                "quantity": 100
            }
        ],
        "offerID": "220823_100-pack_bundle",
        "asset": "https:\/\/shop-cdn.mozambiquehe.re\/dl_store_s14_0_bund_epic_100pack_a189.png"
    },

CodePudding user response:

It looks like item.pricing is actually an array of objects. From here you have a couple of choices, depending on what you want to do.

  1. item.pricing will only ever have one element.
    In this case, you can just take the first element:
    <div className = "bundleName"> {item.title} {item.pricing[0].quantity}</div>
    
  2. You want to list all the quantities
    <div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).join(" ")}</div>
    
    or
    <div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).join(", ")}</div>
    
  3. You want to have the sum of all quantities
    <div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).reduce((a, b) => a   b, 0)}</div>
    
  • Related