본문 바로가기

JS

JS - object

JS 강의 필기 + 추가

object

{ key : value }

a collection of related data and/or functionality

Nearly all objects in JS are instances of the class Object

object 만드는 방식 2가지

const obj1 = {}; // 'object literal' syntax

const obj2 = new Object(); // 'object constructor' syntax

property 추가하기

const ellie = { name: 'ellie', age: 4 }; // object 생성
ellie.hasJob = true; // property 추가
console.log(ellie.hasJob); // true

property 삭제하기

delete ellie.hasJob; // property 삭제
console.log(ellie.hasJob); // undefined

computed property name

[ ] 안에 string type의 식을 넣을 수 있고, 그 결과가 key로 사용된다. 동적으로 key-value를 받아올 때(runtime) 유용하다.

function printValue(obj, key){
    //console.log(obj.key); // undefined. obj에 key라는 property는 없음
    console.log(obj[key]);
}

method shorthand

단축표기법

let obj = {
    add: function (a, b) {
        return a + b;
    },
    sub: function (a, b) {
        return a - b;
    }
}
console.log(obj.add(10, 5)); // 15
console.log(obj.sub(10, 5)); // 5

// 위와 동일 - method shorthand 이용
let obj = {
    add (a, b) {
        return a + b;
    },
    sub (a, b) {
        return a - b;
    }
}

 

여기서 arrow function까지 쓰면 아래와 같이 쓸 수 있다.

let obj = {
    add: (a, b) => a + b,
    sub: (a, b) => a - b
}

property value shorthand

object의 key와 value의 값이 같다면 생략 가능

const person1 = { name: 'bob', age: 2 };

//  return만 하는 함수는 대문자로 시작하도록 명명.
function Person(name, age) { // 함수를 이용해 값만 전달. template 역할.
    return {
        name, // name: name, 대신.
        age, // age: age, 대신.
    };
}

const person2 = Person('phin', 30);

 

return만 하는 함수는 아래와 같이 constructor function 형태로 쓸 수 있다

function Person2(name, age) {
    // this = {};
    this.name = name;
    this.age = age;    
    // return this;
}

const person3 = new Person2('joe', 30);

in operator

check if a property(key in obj) exists

console.log('name' in person3); // true
console.log('job' in person3); // false

// in operator을 사용하지 않았을 때
console.log(person3.job); // undefined

for ... in

for (key in obj) 형태

for (let key in person3) {
    console.log(key); // person3의 properties를 차례로 출력
}

for ... of

for (value of iterable) 형태. object가 아닌 array 같이 순차적으로 iterable한 것을 사용

for(let i = 0; i < array.length; i++) {body} 형태보다 더 쉽게 사용

const array = [1, 2, 4, 5]
for (let value of array) {
    console.log(value); // array의 요소들을 차례로 출력
}

cloning

const user = { name: 'Phin', age: 30 };
const user2 = user; // 각기 다른 reference가 같은 object를 가리키는 상태
user2.name = 'Joe'; // user2를 변경했지만 user도 같이 바뀜
console.log(user); // {name: "Joe", age: 30}

 

분리된 복제 (old way)

const user3 = {};
for (let key in user) {
    user3[key] = user[key];
}

분리된 복제 (new way - assign)

assign<TUV>(targetTsource1Usource2V): T & U & V;

array 전달도 가능

const user4 ={};
Object.assign(user4, user);

// 위를 아래와 같이 쓸 수 있음
const user4 = Object.assign({}, user);

 

assign에 source를 여러개 줄 때 property가 같으면 뒤엣걸로 값을 덮어씌운다

const fruit1 = { color: 'red' };
const fruit2 = { color: 'blue', size: 'big' };
const mixed = Object.assign({}, fruit1, fruit2); // 같은 property인 color는 뒤엣걸로 값을 덮어씌움
console.log(mixed.color);   // blue
console.log(mixed.size);    // big

'JS' 카테고리의 다른 글

JS - JSON  (0) 2020.12.25
JS - array  (0) 2020.12.24
JS - class  (0) 2020.12.22
JS - function  (0) 2020.12.21
JS - operator  (0) 2020.12.21