Home > Enterprise >  Angular: How can I 'nest' an object in another object?
Angular: How can I 'nest' an object in another object?

Time:03-24

I have a component that's creating an object from existing data like this:

sales: any = [];

 this.mydata.price.forEach((salesData) => {
      this.sales.push({
          "name": new Date(salesData.date_ordered),
          "value": salesData.unit_price
      });

When completed, I get an object like this:

[
  {
    "name": "2021-09-26T21:20:23.807Z",
    "value": "79.9900"
  },
  {
    "name": "2021-09-29T18:33:28.683Z",
    "value": "86.7576"
  }
]

I'm trying to use this data in an NGX line chart, so I need to make it part of a series like this:

[
  {
    "name": "Sales",
    "series": [
    {
      "name": "2021-09-26T21:20:23.807Z",
      "value": "79.9900"
    },
    {
      "name": "2021-09-29T18:33:28.683Z",
      "value": "86.7576"
    }
  ]
 }
]

How might I modify the object I'm creating so it's nested inside another?

CodePudding user response:

is pretty simple you just have to adjust the sales array a little bit. I create this stackblitz with the code https://stackblitz.com/edit/angular-ivy-thtzzm

code that does what you need:

export class AppComponent implements OnInit {


sampleData: any = [
    { name: 'name 1', price: 50 },
    { name: 'name 1', price: 12 },
    { name: 'name 1', price: 5 },
    { name: 'name 1', price: 87 },
    { name: 'name 1', price: 99 },
  ];

  sales: any = [{ name: 'Sales', series: [] }];

  ngOnInit(): void {
    this.sampleData.forEach((salesData) => {
      this.sales[0].series.push({
        name: salesData.name,
        value: salesData.price,
      });
    });
  }
}
  • Related