2

I want to create objects in a foreach loop:

I'm starting from this:

data.forEach(function (el) {
        var dynamic_var = new Quill(el['editor']);
         dynamic_var.on('text-change', logHtmlContent);})

But, dynamic_var is 'overwritten', and I want to remain unique.

I check some html elements, and for each one that I found I want to create a new Object, and execute the Object methods.

In my case the variable get a new object per each iteration, is not a new variable.

3
  • 1
    What do you mean 'overwritten'? What is expected and current behavior? Commented Feb 1, 2019 at 14:56
  • @ArtemArkhipov At first I thought OP meant that it gets overwritten by the last element, since var is used instead of let. But then I saw it's inside a foreach function so it shouldn't make a difference. Commented Feb 1, 2019 at 14:59
  • @ArtemArkhipov I mean the variable becomes every time a new Quill object, and I don't want to lose them, but simple creating multiple objects. Commented Feb 1, 2019 at 15:00

1 Answer 1

5

Is this what you were looking for?

var quillValueContainer = {};

// ...

data.forEach(function(el) {
  quillValueContainer[el] = new Quill(el['editor']);
  quillValueContainer[el].on('text-change', logHtmlContent);
});

This will only work if el is a string, or number. Seeing how you are using it like this: el['editor'], makes me thing it's an Object, in which case, you can instead use the indices of the elements.

var quillValueContainer = {}; // [] should also work for indexes

// ...

data.forEach(function(el, index) {
  quillValueContainer[index] = new Quill(el['editor']);
  quillValueContainer[index].on('text-change', logHtmlContent);
});

Also, I don't know if this is something you need to do, but you can check if the Quill Object has already been initialized and skipping a duplication if it has, by doing:

data.filter(function(el, index){ return !quillValueContainer[index]; }).foreach(...

Or

data.forEach(function(el, index) {
  if(quillValueContainer[index]) return;
  quillValueContainer[index] = new Quill(el['editor']);
  quillValueContainer[index].on('text-change', logHtmlContent);
});
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, can you please take a look at this one(related) stackoverflow.com/questions/54483529/…
@user3541631 posted an answer there as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.