Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deep Copy #2

Open
BKJang opened this issue May 6, 2019 · 1 comment
Open

Deep Copy #2

BKJang opened this issue May 6, 2019 · 1 comment
Labels
Skill of JS It is related to skill of JS.

Comments

@BKJang
Copy link
Owner

BKJang commented May 6, 2019

🙏 Reference

@BKJang BKJang changed the title Type of JS 02 ( 값 타입 vs 참조 타입 / Deep Copy ) Type of JS - 02 ( 값 타입 vs 참조 타입 / Deep Copy ) May 6, 2019
@BKJang
Copy link
Owner Author

BKJang commented May 6, 2019

Deep Copy

use JSON.parse , JSON.stringify

function changeAgePure(person) {
    var newPersonObj = JSON.parse(JSON.stringify(person));
    newPersonObj.age = 25;
    return newPersonObj;
}
    
var alex = {
    name: 'Alex',
    age: 30
};
var alexChanged = changeAgePure(alex);

console.log(alex); // -> { name: 'Alex', age: 30 }
console.log(alexChanged); // -> { name: 'Alex', age: 25 }

or use $.extend()

function changeAgePure(person) {
    var newPersonObj = $.extend(true, {}, person);
    newPersonObj.age = 25;
    return newPersonObj
}
    
var alex = {
    name: 'Alex',
    age: 30
};
var alexChanged = changeAgePure(alex);

console.log(alex); // -> { name: 'Alex', age: 30 }
console.log(alexChanged); // -> { name: 'Alex', age: 25 }

or use destructuring (ES6)

function changeAgePure(person) {
    var newPersonObj = { ...person };
	newPersonObj.age = 25;
	return newPersonObj
}
    
var alex = {
    name: 'Alex',
    age: 30
};
var alexChanged = changeAgePure(alex);

console.log(alex); // -> { name: 'Alex', age: 30 }
console.log(alexChanged); // -> { name: 'Alex', age: 25 }

@BKJang BKJang added the Basic of JS It is related to basic concept of JS. label May 6, 2019
@BKJang BKJang changed the title Type of JS - 02 ( 값 타입 vs 참조 타입 / Deep Copy ) Skill of JS - Deep Copy May 6, 2019
@BKJang BKJang changed the title Skill of JS - Deep Copy Deep Copy May 6, 2019
@BKJang BKJang added Skill of JS It is related to skill of JS. and removed Basic of JS It is related to basic concept of JS. labels May 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Skill of JS It is related to skill of JS.
Projects
None yet
Development

No branches or pull requests

1 participant