Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

angular break sub array values to main object. subarray size is dynamic

angular break sub array values to main object. subarray size is dynamic

myArray = [{'ID' : 1,
        'addDetail' : ['test 1', 'test 2']}]

expected array

myArray = [{'ID' : 1, 'line1' : 'test 1', 'line2' : 'test 2'
        'addDetail' : ['test 1', 'test 2']}]

i used bellow login

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.partiesdatalist = this.partiesdatalist.map(item => {
const addDetail = item.addDetail;
addDetail?.forEach((detail, index) => {
  item[`line${index + 1}`] = detail;
});
return item;
});

but it showing error

Element implicitly has an ‘any’ type because expression of type ‘line${number}‘ can’t be used to index type

in the line of

item[`line${index + 1}`] = detail;

>Solution :

You have to first defining typing for all the properties. We can use [key: string]: any to allow for dynamic properties on the interface.

export interface PartiesDetail {
  [key: string]: any;
  ID: number;
  addDetail: Array<string>;
}

Full Code:

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

export interface PartiesDetail {
  [key: string]: any;
  ID: number;
  addDetail: Array<string>;
}

@Component({
  selector: 'app-root',
  standalone: true,
  template: ``,
})
export class App {
  partiesdatalist: Array<PartiesDetail> = [
    { ID: 1, addDetail: ['test 1', 'test 2'] },
  ];
  ngOnInit() {
    this.partiesdatalist = this.partiesdatalist.map((item: PartiesDetail) => {
      const addDetail = item.addDetail;
      addDetail?.forEach((detail: string, index) => {
        item[`line${index + 1}`] = detail;
      });
      return item;
    });
  }
}

bootstrapApplication(App);

Stackblitz Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading