-1

I am trying to access nested property productTitle in below order JSON, however, could only manage to get the items using

JSON.stringify(orders[i].cart.items, null, 4);

I have tried the nested loop but to no avail. I have also tried

JSON.stringify(orders[i].cart.items.item, null, 4);

which is also not working. Missing something fundamental, I have spent hours looking through JSON docs and tutorials but could not find specific help.

[
  {
    "_id": "5ea5115224bf1f569c4fac96",
    "user": "5ea19f4160539d264ca1e7c5",
    "cart": {
      "items": {
        "5e92b488fc3e326b70be262d": {
          "item": {
            "_id": "5e92b488fc3e326b70be262d",
            "productCode": "PROD002",
            "productType": "Duvet",
            "productTitle": "Kingsize Duvet",
            "__v": 0
          },
          "qty": 1,
          "price": 3
        },
        "5e92f5f9213dc863e0e97682": {
          "item": {
            "_id": "5e92f5f9213dc863e0e97682",
            "productCode": "PROD006",
            "productType": "Duvet",
            "productTitle": "double-Duvet",
            "__v": 0
          },
          "qty": 2,
          "price": 5
        }
      },
      "totalQty": 3,
      "totalPrice": 8
    },
    "address": "London",
    "name": "John Cena",
    "paymentId": "ch_1Gc2KUIyQsnk8nhOTUR602KW",
    "__v": 0
  }
]

Please be gentle, I am a newbie!

Update: Manage to get the nested keys and values using below iteration: for(var i=0;i

        for (var key of Object.keys(orders[i].cart.items)) {


      console.log("Title: "+ orders[i].cart.items[key].item.productTitle );
      console.log("Quanitity: "+  orders[i].cart.items[key].qty);
      console.log(" Price:  "+orders[i].cart.items[key].item.productPrice );
      console.log(" Subtotal: "+orders[i].cart.items[key].item.productPrice * orders[i].cart.items[key].qty);


      console.log("Total Quantity is :"+orders[i].cart.totalQty+" & Total Price: £ " + orders[i].cart.totalPrice);


      }
  • Shouldn't `items` be an array of `item` objects? In your JSON, `items` is an object with nested objects. The nested object seems to be the `id` and there's another `_id` that contains the same value. I think what you intended to do was an array of `items` with objects that contained everything in them. Take a look at that. – Azeem Apr 26 '20 at 06:29
  • Also, there are two closing parentheses here: `JSON.stringify(orders[i].cart.items, null, 4));` Maybe, you copied it from your code as-is and it was used in another function call. – Azeem Apr 26 '20 at 06:33
  • @Azeem thanks, yes additional parenthesis were from the console log. In regards to the same ID twice, I need to have an ID associated with the cart (which can contain multiple products and each product could be added more than one time), therefore it would require the ID to be inside Cart. – omercheema619 Apr 26 '20 at 06:41
  • Are you sure that that it is valid JSON that you have and the `i` is a valid index? – Azeem Apr 26 '20 at 06:52
  • Each object stored within the array is a valid JSON object. Note that issue I am facing is accessing the item properties, i.e. "productTitle", as I can access items fine by using reference, however as I have dynamic ID within item which I cannot reference. – omercheema619 Apr 26 '20 at 07:04
  • Right. Why is `items` not an array? – Azeem Apr 26 '20 at 07:06
  • For no obvious reasons, tbh, just for consistency as rest of the structure is JSON objects. – omercheema619 Apr 26 '20 at 07:17
  • 1
    Well, IMO, it should be an array as it is a collection of `item` objects. It would simplify the JSON itself as well as the traversal and bulk processing. Otherwise, you'd have to extract the ID to reference each `item` object and then process/traverse. – Azeem Apr 26 '20 at 07:24
  • Noted, will try to change these to the arrays. But is there a way to extract those Item ID's? as they do not have name and are numeric? I do not think we reference values using numeric names? – omercheema619 Apr 26 '20 at 07:30
  • You can use `Object.keys()` method to get the keys. If you haven't already done it then here's a live [example](https://repl.it/@AzeemSajid/BouncyOldlaceScale) with your JSON. – Azeem Apr 26 '20 at 13:39

1 Answers1

-1

I think you have missed fetching 5e92b488fc3e326b70be262d in your call dot reference call after items .

orders[i].cart.items['5e92f5f9213dc863e0e97682'].item.productTitle

This worked for me .

5e92b488fc3e326b70be262d is also an object in your json so you have to access 5e92b488fc3e326b70be262d object before accessing item .

'5e92f5f9213dc863e0e97682'has been added in your json as a map and not as an object. That's why not working with dot operator.

This is what I did .

this.http.get("assets/client.json").subscribe(data =>{
      console.log(data[0].cart.items['5e92f5f9213dc863e0e97682'].item.productTitle);
      var items = data[0].cart.items;
      console.log(items['5e92f5f9213dc863e0e97682'].item.productTitle);
    })

Both console statements gave double-Duvet as output .

  • 1
    Tried that as well but no luck as it gave a syntax error probably due to numeric reference. – omercheema619 Apr 26 '20 at 06:50
  • Try with this now . It will work for you as well . – Anishek Raman Bharti Apr 26 '20 at 07:18
  • *”as a map and not as an object”* makes no sense. The reason your previous sample with a `.` didn’t work was that a property starting with a numeral is invalid syntax. The bigger problem is that OP won’t know what those property names are and can’t hardcore them. – deceze Apr 26 '20 at 07:27
  • here items is a list with data as key value pair as a map . you have to give same key to fetch value here as we give for arrays like arr[i] but since data is in key value pair so simple index location wise fetching will not work . – Anishek Raman Bharti Apr 26 '20 at 07:32