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
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);