Search code examples
angular2-formsangular2-services

How to excess the array which is inside complex JSON Object?


I have a complex JSON Object like this

{
    "product": {
        "expiry_type": {
            "type": "premium"
        },
        "accout_holders": {
            "admin": {
                "name": "Admin",
                "description": "Admin"
            }
        },
        "productId": "apple-inc",
        "description": "Apple Incorporation"
    },
    "sales": {
        "datasource": [{
            "name": "USA",
            "type": "direct",
            "uri": "https://www.apple.com/"
        }],
        "apps": {},
        "saleID": "SEIO578ed57EI"
    }
}

I got this JSON object by the help of service. I want to access the data source and keep it into another array so that I can show the data source name in the angular material chip. How can I access the data source array?


Solution

  • Its very simple, every JSON Object is given with a name like this:

     {
        	"product": {
        		"expiry_type": {
        			"type": "premium"
        		},
        		"accout_holders": {
        			"admin": {
        				"name": "Admin",
        				"description": "Admin"
        			}
        		},
        		"productId": "apple-inc",
        		"description": "Apple Incorporation"
        	},
        	"sales": {
        		"datasource": [{
        			"name": "USA",
        			"type": "direct",
        			"uri": "https://www.apple.com/"
        		}],
        		"apps": {},
        		"saleID": "SEIO578ed57EI"
        	}
        }

    Now accessing the array which is datasource in the above case is done like this name.product.sales.datasource[0]

    You don't have to take the datasource to another array in order to show them in a chip. You can iterate your datasource and can use string interpolation for showing any object in an angular material chip. Here is how you can get it.

    <mat-chip *ngFor="let ds of name.product.sales.datasource"  matTooltip="{{ds.url}}">
            {{ds.name}}
          </mat-chip>

    this will display all the datasource name object in a chip and if you hover your cursor over the chip you can see url as tooltips.