0

I am declaring an array on a provider @Injectable to use it in different components.

  normeList: any[] = [
    {
      name: 'choice 1',
      type:'false'
    },
    {
      name: 'choice 2',
      type:'false'
    }
  ];

On the component, I assigned that array like this:

this.myArray = [].concat(this.sharedListDeclarationProvider.normeList);

on the view, I am working with the myArray and I am changing the type on the myArray from false to true;

the problem is that 'myArray' on the component and normList declared on the provider also changing.

How can I change the value of the myArray without changing the normeList

3
  • What exactly are you trying? You want to copy normeList of your provider to myArray? Commented Oct 8, 2018 at 9:17
  • yes without changing normeList if I change the myArray Commented Oct 8, 2018 at 9:30
  • See my answer below Commented Oct 8, 2018 at 9:33

2 Answers 2

1

I presume you want to clone the normeList array from provider and use it in your component.

If you want to copy the array without mutation or side effects you could use slice method of array but this would only works for simple arrays. For complex arrays you can use

  • JSON.parse(JSON.stringify(array))
  • ES6 version using spread operator [...array] along with map
  • combination of map with Object.assign should work

So for your case you can rewrite the below line

this.myArray = [].concat(this.sharedListDeclarationProvider.normeList); 

with

this.myArray = this.sharedListDeclarationProvider.normeList.map(item=>Object.assign({}, item));

or even shorter using ES6 spread operator

this.myArray = this.sharedListDeclarationProvider.normeList.map(item=>{}..item));
Sign up to request clarification or add additional context in comments.

Comments

1

You can use JSON.parse and JSON.stringify

this.myArray = JSON.parse(JSON.stringify((this.sharedListDeclarationProvider.normeList));

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.