0

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);
2
  • Your code is correct. what is it logging? Commented Dec 5, 2018 at 20:00
  • Note the SO snippet console is not perfect. Open Chrome devtools (or similar) before you click Run and you should see the result you expect in the devtools console. (Screenshot) Commented Dec 5, 2018 at 20:02

3 Answers 3

3

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));
Sign up to request clarification or add additional context in comments.

Comments

2

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))

Comments

1

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);
})

Comments

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.