microsoft / powerbi-report-authoring

A library for authoring Power BI reports while embedded into your apps. Provides service which makes it easy to change report and visual elements in session. It gives APIs such as creating visual, changing visual properties, etc ...
MIT License
40 stars 18 forks source link

removeDataField: will remove the same datafield which has diffrent index #11

Closed Fuminhsg closed 1 week ago

Fuminhsg commented 4 years ago

I was trying to use visual.addDataField first to add new data fields and then use visual.removeDataField to remove old data fields.

For example, the initial dataFields is [dataField 1, dataField 2]. After addDataField, I got dataFields = [dataField 1(old), dataField 2(old), dataField 1(new), dataField 2(new)]. I want to remove the first two old dataFields in the array. But when I use:

            visual.getDataFields(dataRole).then((dataFields) => {
                  dataFields.forEach((datafield, index) => {
                    if (index < 2) {
                      visual.removeDataField(dataRole, 0);
                    }
                  });
                });

I expect to get dataFields = [dataField 1(new), dataField 2(new)], but I got dataFields = [ ] instead.

v-MadhavC commented 3 weeks ago

To remove the first two data field, you can use the following code:

const dataFields = await visual.getDataFields(dataRole);
const noOfDataFieldsToDelete = 2;
for (let i = 0; i < noOfDataFieldsToDelete; i++) {
    if (i < dataFields.length) {
        await visual.removeDataField(dataRole, 0);
    }
}

This code snippet removes the first two data fields by always targeting index 0. As the array shrinks with each removal, it ensures that only the specified fields are removed.