(SK쉴더스)AI 활용한 클라우드 & 보안 전문가 양성 캠프

[새싹 성동 2기] 3-1. Javascript 객체 처리 방법

hunm719 2024. 11. 15. 21:35

 

목차

 

1. 단축 속성명    

2. 계산된 속성명

3. 전개 연산자    

4. 비구조화        

 

 

1. 단축 속성명 (Shorthand Property Names)

객체를 생성할 때, 변수 이름과 객체의 키 이름이 동일하다면 자동으로 할당되어 생략할 수 있음

// 변수의 경우
const name = "김지훈";
const age = 33;

const person1 = {
    name: name,
    age: age
};

const person2 = {name, age};  // 변수 이름을 키로 자동 할당

console.log(person1);         // {name: '김지훈', age: 33}
console.log(person2);         // {name: '김지훈', age: 33}

// 함수의 경우
const plus = {
    add1: function (a, b) {
        return a + b;
    },
    add2(a, b) {                // 단축된 메서드 정의
        return a + b;
    }
};

console.log(plus.add1(1, 2));   // 3
console.log(plus.add2(1, 2));   // 3

 

 

2. 계산된 속성명 (Computed Property Names)

객체의 키 이름을 동적(변수 or 연산)으로 정의할 수 있음

function returnObject1(key, value) {
    const obj = {};
    obj[key] = value;
    return obj;
}

function returnObject2(key, value) {
    return {[key] : value};                        // 계산된 속성명을 사용하여 동적으로 객체 생성
}

console.log(returnObject1("name", "김지훈"));	    // { name: '김지훈' }
console.log(returnObject2("name", "김지훈"));	    // { name: '김지훈' }

function returnObject3(key, value, no) {
    return { [key + no] : value};                  // // 계산된 속성명과 문자열 결합을 함께 사용
}

console.log(returnObject3("name", "김지훈", 1));   // {name1: '김지훈'}
console.log(returnObject3("name", "슈나쟝", 2));   // {name2: '슈나쟝'}

 

 

3. 전개 연산자 (Spread Operator)

배열이나 객체의 요소를 나열(전개)하는 방법으로, 배열이나 객체의 값을 복사하거나 병합할 때 사용됨

// 배열 복사시 주소 공유의 문제 해결
const arr1 = [1, 2, 3];
const arr2 = arr1;          // 직접 할당시 배열 데이터의 주소를 공유함
arr1[0] = 4;
console.log(arr1, arr2);    // [4, 2, 3] [4, 2, 3]

const arr3 = [1, 2, 3];
const arr4 = [...arr3];     // 전개 연산자를 활용하면 배열의 값을 복사함
arr3[0] = 4;
console.log(arr3, arr4);    // [4, 2, 3] [1, 2, 3]

// 배열 병합 가능
const arr5 = [11, 22, 33];
const arr6 = [44, 55, 66];
const arr7 = [...arr5, ...arr6];
console.log(arr7);          // [11, 22, 33, 44, 55, 66]


// 객체 복사 및 병합 가능
const obj1 = {name: "김지훈", age: 33};
const obj2 = {...obj1};
console.log(obj2);          // {name: '김지훈', age: 33}

const obj3 = {name: "슈나쟝", isCute : true};
const obj4 = {...obj1, ...obj3};
console.log(obj4);          // {name: '슈나쟝', age: 33, isCute: true}

 

 

4. 비구조화 (Destructuring)

배열 또는 객체에서 특정 값을 추출하여 변수에 할당하는 문법

const arr = [1, 2, 3];

const first = arr[0];
const second = arr[1];
const third = arr[2];
const [one, two, three] = arr;      // 비구조화를 사용해 배열의 요소를 변수에 할당

console.log(first, second, third);  // 1, 2, 3
console.log(one, two, three);       // 1, 2, 3


const abnormality = {name: "Nothing there", grade: "ALEPH"};

const {name, grade} = abnormality;  // 비구조화를 사용해 객체의 요소를 변수에 할당
console.log(name, grade);           // Nothing there ALEPH

 

 

※ 위의 개념들을 함께 조합해서도 사용할 수 있음

const key = 'score';
const person = { name: 'Alice', age: 25 };

// 객체에 새로운 속성 추가 (계산된 속성명 + 전개 연산자)
const updatedPerson = { ...person, [key]: 100 };

// 객체 비구조화로 값 추출
const { name, age, score } = updatedPerson;

console.log(updatedPerson); // { name: 'Alice', age: 25, score: 100 }
console.log(name, age, score); // Alice 25 100