Create an object based on items in a list - javascript

78 views Asked by At

this.items is a list of items read from a database. For each item in the list I want to create the Shape.Rect-object and load them into a function called stencil.load. This function cannot add items dynamically, so I need to create all the items and load them simultaneously.

I've tried doing a forEach as shown in the codesample below, but it only registers the last item from the list. Any idea what to do?

.
.
.

this.items.forEach((item) => {

  const result = new Shape.Rect({
    shape: 'rect',
    label: item.component_name,
    id: item.component_id,
    x: 5,
    y: 50,
    width: 100,
    height: 25,
  });

  stencil.load([result], 'group1');

});

.
.
.
1

There are 1 answers

0
plalx On BEST ANSWER

Haven't looked at the stencil.load API, but from what you described and the usage I think you can just map all items to Shape.Rect first then load them all.

e.g.

const rects = this.items.map(item => new Shape.Rect({
    shape: 'rect',
    label: item.component_name,
    id: item.component_id,
    x: 5,
    y: 50,
    width: 100,
    height: 25,
}));

stencil.load(rects, 'group1');