Search code examples
javascriptarraysjsonpugjade4j

How te read Object in Jade Pug?


I have this JSON that I send to the PUG page from router.get with the name of prices

[{"space2":{"actualPrice":"$ 99.990","oldPrice":"$ 129.990","id":11098071}},{"h20":{"actualPrice":"$ 69.990","oldPrice":"$ 79.990","id":4444311}},{"space":{"actualPrice":"$ 79.990","oldPrice":"$ 99.990","id":4436762}}]

and in a pug page I want to show actualPrice of space2 but I dont know how.

I tried with prices.space2.actualPrice and in a for cycle and nothing


Solution

  • Your question looks like a Javascript question rather than a Pug question. The following:

    -
      const Data = [
        {"space2":{"actualPrice":"$ 99.990","oldPrice":"$ 129.990","id":11098071}},
        {"h20":{"actualPrice":"$ 69.990","oldPrice":"$ 79.990","id":4444311}},
        {"space":{"actualPrice":"$ 79.990","oldPrice":"$ 99.990","id":4436762}}
      ]
    
    p Only space2: 
      each d in Data 
        if d.space2 
          | #{d.space2.actualPrice}
    

    will output:

    Only space2: $99.9990


    Are you certain you want to structure your data object in this manner? You can access the details of each element of the array only if you know the first property key of each element. For example, it will be pretty tough to list out the actualPrice of every item in your array.

    Depending on what your situation is, it might be more useful if your data is organized as:

    const Data = [
      {"name": "space2", "actualPrice":"$ 99.990","oldPrice":"$ 129.990","id":11098071},
      {"name": "h20", "actualPrice":"$ 69.990","oldPrice":"$ 79.990","id":4444311},
      {"name": "space", "actualPrice":"$ 79.990","oldPrice":"$ 99.990","id":4436762}
    ]