Exploring the depths of OfficeScript: A guide to accessing nested objects using interfaces and setValues()

Currently, I am diving into Excel Office Script through API requests. Even though I'm not a programmer by trade, I find myself facing challenges that I wouldn't encounter in jQuery. The struggle lies in structuring objects correctly to set values on the page and utilize the object in Power Automate.

The issue seems to stem from how I need to construct my arrays in relation to the "interfaces". I'm still grappling with figuring out the correct structure needed for this task. The error arises at setValues due to incorrect dimensions for the operation.

I'm working on importing JotForm submissions directly into Excel Online, which prevents me from sharing my full code. However, I can provide an edited JSON snippet along with an explanation of my approach.

1° Excel Office Script


async function main(workbook: ExcelScript.Workbook): Promise<void> {
        
    const workSheet = workbook.getActiveWorksheet();
    let fetchResult = await fetch(myApiQuery)
    
    let json: JSONData[] = await fetchResult.json();
    
    // Filtering out unnecessary data after retrieving the complete answer in the Json Object from "content"
    const result: JSONData[] = json["content"]
    const rows: (string | boolean | number)[][] = [];

    // Iterating through the object as intended.
    for (const [key, value] of Object.entries(result)) {
       
        rows.push([value["id"], value["created_at"], value["answers"]])
              
        for (const [subKey, subValue] of Object.entries(value["answers"])) {
            if (typeof subValue["answer"] !== "undefined") {
               rows.push([subValue["answer"]])
            }
            else {
                rows.push([""])
            }
     }

 console.log(rows);
 const targetRange = workSheet.getRange('A2').getResizedRange(rows.length - 1, rows[0].length - 1);
 targetRange.setValues(rows);

return;
}

// Key sections for Power Automate
   interface JSONData {
    id?:number
    created_at?:number
    answers?:SUBDATA;
}

interface SUBDATA{
        answer?:string;

}

2°) Below is the truncated JSON Object obtained from console.log(rows). Personal information has been redacted for privacy purposes. Notice how the "ANSWERS" section sometimes includes a defined "answer" field while other times it does not. Making this distinction helps maintain the correspondence between questions and answers.

[
{
    "id": "---",
    "form_id": "---",
    "ip": "---",
    "created_at": "2021-09-18 07:39:14",
    "updated_at": null,
    "answers": {
        "1": {
            "name": "vousAvez",
            "order": "6",
            "text": "QUESTION",
            "type": "control_head"
        },
        "2": {
            "name": "email",
            "order": "7",
            "text": "Email",
            "type": "control_email",
            "answer": "email Address" 
        }
    }
],
[""],
[""],
[""],
["emailAdress"],
["Name"],
["FristName"],
[""],
[""],
]

Lastly, here's a sample of working JQuery code for reference.

 $.each(responseText["content"], function (index, element) {
   items.push("<br/><span style='color:red'>" + element["id"] + " - " + element["created_at"] + "</span><br/><br/>");
   $.each(element["answers"], function (subIndex, subElement) {
      if (typeof subElement["answer"] !== "undefined") {
         items.push("<li id='" + subIndex + "'>" + subElement["name"] + "<span style='color:blue'> " + subElement["answer"] + "</span></li>");
      }
      else {
         items.push("<li id='" + subIndex + "'>" + subElement["name"] + ": </li > ");
      }
      items.push('<br/>');
      })
})
 $("<ul/>", {
   "class": "my-new-list",
   html: items.join("")
}).appendTo("body");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Substituting generic type in inherited class method results in error message: "Property 'x' in type 'y' cannot be assigned to the property with the same name in the base class 'Parent'."

Here is the code snippet I am working with: class BaseModel { protected getAttribute<T extends BaseModel>(): keyof T | null { return null; } } class Payment extends BaseModel {} class Item extends BaseModel {} class Sale extends BaseModel { ...

Toggle button in Angular 9 to control visibility of a div element

Within my Angular application, I have two distinct components. The first component is a top navigation bar with a toggle button. The second component is a Dashboard located in a separate module. The Dashboard consists of two div elements where one or the ...

After uploading TypeScript Node package types to NPM, they fail to compile with the error message: "Declaration file for module not found."

I recently shared a new Node package called maps-backend-challenge, on npm (you can find the code on GitHub here). After running npm run build successfully, I proceeded to do npm publish. However, when I tried importing this module into a fresh TypeScript ...

Is there a way to create a typesafe Map in TypeScript with a key and value both being of the same generic type X?

The desired outcome should be as follows: const newObj: ??? = { [Fruit<Apple>]: Taste<Apple>, [Fruit<Banana>]: Taste<Banana>, } const selectedKey: Fruit<Apple> = ...; newObj[selectedKey] // should only return Taste<A ...

Converting date format from d-mmm-yyyy to yyyy-mm-d using Angular 2

How can I convert the date format from d-mmm-yyyy to yyyy-mm-d using Angular 2's datepipe? I need to change dates like 1-Nov-2019 to 2019-11-1 or 15-Dec-2018 to 2018-12-15 It's essential that I achieve this transformation using the built-in fun ...

Mastering the art of linking together recursive Ajax load promises in TypeScript

I'm making an effort to adhere to good jQuery practices and utilize promises, but I still struggle with some basic concepts. Below is a panel loading method that might need to redirect to another page instead of loading the originally specified one. ...

Encountering Syntax Error while running `ionic serve` in IONIC2

I'm stuck on this Syntax error and I can't figure out what went wrong. It keeps showing up even though I copied the code directly from the official ionic2 docs. SyntaxError: D:/Manson/Arts/Ionic/IonicTodo2/app/pages/list/list.js: Unexpected toke ...

"Customizing the MsAdalAngular6Module setup on the fly - a step-by-step

In order to manage authentication in an Angular single page app, I am utilizing the microsoft adal wrapper available at https://github.com/manishrasrani/ms-adal-angular6. Following the documentation, I configure all necessary options during compile time u ...

What is the best way to remove an element from an array and add a new one?

Here is the array that I am working with: [ { "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2" ...

Is there a way to retrieve all elements from the array with the specified type definition of item(index: number): any?

I am currently working on a React Native project, but I have a TypeScript query. The SQLite embedded database is set up and I am trying to retrieve the entire array of rows. However, I am facing an issue with the object structure. https://i.sstatic.net/74 ...

What is the best way to save data from a Firebaselistobservable into an array?

I've been attempting to transfer data from Firebase to an array using Angular 2, but I'm facing difficulties in pushing the data into the array. Below is the code snippet: Variables: uid: string = ''; agencyItems: FirebaseListObserva ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

What are the best methods for querying and updating a self-relation in Prisma?

I recently obtained some self-relation tables directly from a specific Prisma example. model User { id Int @id @default(autoincrement()) name String? followedBy Follows[] @relation("follower") following Follows[] @rel ...

Encountering problem with npm ERR! peer @angular/common@"^12.0.0" while trying to install @ng-bootstrap/[email protected]

Encountering an issue during the deployment of my Angular application. I added the @ng-bootstrap/ng-bootstrap package, but there seems to be a dependency resolution problem causing the issue. 22-Dec-2022 07:03:47 npm ERR! Could not resolve dependency: 2 ...

Tips for avoiding Union types in TypeScript from anticipating unnecessary keys?

My function getRespectiveConfig() returns a Union type that includes all the necessary types: interface AlphaConfig { title: string; } interface BetaConfig { id: string; } export interface EncompassingConfig { alphaConfig?: AlphaConfig; b ...

Experiencing migraines while integrating Firebase 9, Redux Toolkit, and Typescript in a React project. Encountering a peculiar issue where 'dispatch' is unexpectedly identified as type 'never'?

I am currently in the process of upgrading an old project to newer technologies, specifically focusing on Typescript, redux-toolkit, and Firebase v9 for modularity. While I have limited experience with Typescript and none with redux-toolkit, I have been us ...

Tips on enabling click function in an ionic infowindow

After creating a div in my HTML file and referencing it in my TS file using document.getElementByID, I utilized its inner HTML as the content for an infowindow. However, despite my efforts, I am unable to get clicks working. Adding event listeners to any e ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...

Using RXJS with the 'never' subject as the specified generic type

In my current Angular project, I am using RXJS and Typescript. The code snippet below shows what I have implemented: const sub = new Subject<never>(); My understanding is that the above line implies that any subscriber defining the 'next' ...

TypeScript - Utilizing multiple parameters in a callback function

I am struggling with the code below: function builder<T extends Foo>( getItems: (...) => Promise<T[]>, /* uncertain about what to include in the parentheses here */ ) { return async (...): Promise<Baz> => { const items = a ...