Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object index inside for loop in JavaScript

I have the following problem using javascript (using node.js and mongoose):
I have 2 objects, the first object_1 = {"title": "Equipment 1", "description": "My equipment 1"} and the second object_2 = {"title": "Equipment 2", "description": "My gear 2"}.
The problem I’m having is that I’m trying to overwrite my second object with the information from the first, and I’m using the following code for this:

for (let i in object_1) {
    object_2.i = object_1.i;
}

And the problem I see happening, is that the index variable "i" inside the loop is not being "attached" when I search for object_2.i and object_1.i.

I tested it outside the loop and my code works very well, I would like to know how I use this ‘for’ loop index in this case?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The other answer is the real answer, but I also wanted to point out that another way to attain your desired functionality is to use Object.assign, which is supported by more browsers as compared to the spread operator (...):

Object.assign(object_1, object_2);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading