Home > other >  Loop through key value pair
Loop through key value pair

Time:08-07

How do I loop through a key value pair array?

I declare mine as such:

produse!: {[key: string] : ProductDTO}[];

Then I loop through it like so:

for (let produs of this.produse) {
  category.produse.push((produs as ProductDTO).toSerialized());
}

But I get this error:

Conversion of type '{ [key: string]: ProductDTO; }' to type 'ProductDTO' may be a mistake

I also tried this:

for (let produs of Object.values(this.produse))

with the same effect.

CodePudding user response:

this.produse is an array of objects (Array<{[key: string] : ProductDTO}>). At the end of type [] means that it is an array. So you need to loop array first, then objects:

for (const produses of this.produse) {
  for (const produs of Object.values(produses) {
    category.produse.push(produs.toSerialized());
  }
}

You can also rewrite that using flatMap:

const serialized = this.produse.flatMap(
  produses => Object.values(produses).map(v => v.toSerialized())
);

// Rewrite category.produse
category.produse = serialized;

// Or append new products and keep older
category.produse.push(...serialized);

CodePudding user response:

Using the following syntax proved to work but it is not as elegant as I would want.


 for(let produs of this.produse){
      category.produse.push((Object.values(produs)[0] as ProductDTO).toSerialized())
}

CodePudding user response:

Judging purely by the types provided, you'll need two loops:

for (const produsMap of this.produse) {            // produsMap is of type {[key: string] : ProductDTO}
  const produsList = Object.values(produsMap);     // produsList is of type ProductDTO[]
  for (const produs of produsList) {               // produs is of type ProductDTO
    category.produse.push(produs.toSerialized());
  }
}
  • Related