habudu
habudu

Reputation: 303

How to loop over objects nested in objects in TypeScript

I have an object two layers deep that I'm trying to loop over:

const sections: object = {sectionA: {density1: "content_1"}, sectionB: {density1: "content_1"} 

function makeSectionGrid(sections: object){
  const sectionGrid: JSX.Element[] = []

  for (let section in sections){
    for (let density in section){
      let content: string = section[density]
      sectionGrid.push(<div>{content}</div>)
    }
  }
}

The TypeScript compiler complains about for (let density in section):

The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'

Am I supposed to cast section? I've tried that, and it isn't working. Not sure how to make the error go away.

Upvotes: 1

Views: 403

Answers (1)

strdr4605
strdr4605

Reputation: 4352

You may want to add some interfaces:

interface SectionInterface {
    [density: string]: string;
}

interface SectionsInterface {
    [key: string]: SectionInterface; 
}

const sections: SectionsInterface = {
    sectionA: { density1: "content_1" }, sectionB: { density1: "content_1" }
}

function makeSectionGrid(sections: SectionsInterface) {
  const sectionGrid: any[] = []

  for (let section in sections){
    for (let density in sections[section]){
        let content: string = sections[section][density];
        sectionGrid.push(content);
    }
  }
}

Playground Link

Upvotes: 3

Related Questions