2

How to assign typescript class object array by value not by reference. Below is the code

class Person {
    constructor(public Name: string, public Age: number) {
    }
}

let orignalArr: Person[] = [
    new Person('Gyan', 28),
    new Person('Parkash', 28),
];
let arr2 = orignalArr;    
//let arr2 = orignalArr.slice(0); i tried this but not working
arr2[0].Name = 'changed';
console.log(orignalArr);
//logs 0: Person {Name: "changed", Age: 28} 1: Person {Name: "Parkash", Age:
//  28}

console.log(arr2);
//logs 0: Person {Name: "changed", Age: 28} 1: Person {Name: "Parkash", Age:
//  28}

So what i need is the value of original array should not be changed.

1 Answer 1

3

slice will not work, because your items are also reference type and it will just return the copies of the references.

You can use map function to iterate over array items and then using Object.assign, you can copy the properties of each object into the new object.

The example is provided in Javascript.

class Person {
    constructor(name, age) {
       this.name = name;
       this.age = age;
    }
}

let originalArr = [
    new Person('Gyan', 28),
    new Person('Parkash', 28),
];

let arr2 = originalArr.map(item => Object.assign({}, item));
arr2[0].name = 'Changed';

console.log(originalArr[0]);
console.log(arr2[0]);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this is working, but i doubt it has impact on performance
You will not notice that impact

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.