Replacing array elements in Javascript produces unexpected results

I'm trying to replace array elements (generic objects) with their alternatives (specific Objects), but objects within the original array remain unchanged.

class SpecificObject{
}

this.Objects = [{},{}];

this.Objects.map((signer,index) => {
   //convert json generics to js objects
   this.Objects[index] = new SpecificObject(signer);
});

console.log(this.Objects);

Not sure if the code snippet illustrates the problem correctly, but what i expect to see is:

[
SpecificObject{},
SpecificObject{}
]

I even tried cloning the original object to do the iteration but it didn't help. Must be missing something stupid. Is there a way to achieve what i need with lodash?

Edit(followed the answer advise): Now i do the following:

console.log('signers-before', this.Signers);
this.Signers.map(signer => new SigningTableSigner(signer));
console.log('signers-after',this.Signers);

And this is what i get in my log(object still remain generic):

enter image description here

Edit2

Oops, i forgot the assignment. this.Signers =

now like this everything works as expected:

console.log('signers-before', this.Signers);
this.Signers = this.Signers.map(signer => new SigningTableSigner(signer));
console.log('signers-after',this.Signers);

3 answers

  • answered 2018-12-05 20:00 Amy

    There is no need to modify the collection while you are iterating it. Just return the object from the map.

    this.Objects = this.Objects.map((signer,index) => new SpecificObject(signer));
    

  • answered 2018-12-05 20:00 Krzysztof Atłasik

    You don't use map correctly. You should be just returning objects inside arrow functions. map actually returns new array, which contains elements which were created by applying function you have provided. Because of that you also have to reassign result ot this.Objects.

    this.Objects = this.Objects.map(signer => {
       //convert json generics to js objects
       return new SpecificObject(signer);
    })
    

  • answered 2018-12-05 20:04 Vatsal

    Map is used when you wants to return an array. You can just use forEach for what you are trying to do. But I think this will look better

    this.Objects = this.Objects.map(signer => new SpecificObject(signer))