공부/JAVASCRIPT

[javascript] Object

알로하리미 2021. 3. 8. 13:43
728x90

1.기본개념

- key와 value의 집합체

- 선언

const obj = {};             //object literal
const obj = new Object();   //object constructor

const a = { name : "알로하리미", age : 30 } ;
a.job = "doctor" ; //동적 코딩
delete a.job ;     //동적 삭제

//너무 동적으로 코딩하지 말아야 한다. 규모가 커지는 프로젝트일수록 유지보수가 힘들어진다.

 

2. computed Properties

a['job']
:  computed Properties 정확하게 어떤 key 가 필요한지 모를떄.
   즉, runtime에서 결정될때 이 properties를 쓰게 된다.

a.job 
: 코딩하는 순간 그 key에 해당값을 받아오고 싶을때는 .  으로 연결하여 가져온다.
function printValue( obj, key ){
    console.log(obj[key]); //어떤키가 들어올지 모를때
}

printValue( objA, 'name' );

 

3. Property value shorthand(단축 속성명)

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

//4번째 사람 편하게 만들기
//동일한 key가 사용되는 object를 만들때는 함수로 만들어
//객체를 리턴한다.
function makePerson(name, age){ // class없었을때 이런식으로 많이 작성했음.
    return {
    	name, //name: name ( key와 value의 이름이 동일하다면 이렇게 생략가능 )
        age   //age: age
    }
}

const persont = makePerson('elile',30);

 

4. constructor function 명명

다른계산 하지 않고 순수하게 Object생성하는 함수들은 대문자로 시작하게 함수를 만들었음.

function Person(name, age)
{
    //this = {} ; 생략가능
    this.name = name ;
    this.age= age;
    //return this; 생략가능
}

person4 = new Person('알로하리미', 30);

 

5. in 연산자 : object에 특정 key가 있는지 없는지 확인

console.log('name' in obj ) ; //obj라는 object안에 'name'이라는 key가 있으면 true 아니면 false

 

6. for...in vs for...of 

for ( key in obj ){ //object의 key값을 심플하게 가져올수 있다.
    console.log(key);
}

for(value of iterable) {// iterable array등
    console.log(value);
}

 

7. obj 복사

object.assign( dest, [obj1, obj2, obj3 .....] ) ;

const target = { a: 1, b: 2 };
const target2 = {};
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);
const returnedTarget2 = Object.assign(target2, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(target2);
// expected output: Object {}
console.log(returnedTarget2);
// expected output: Object {b: 4, c: 5 }

key가 겹치면 sorcue에 해당하는 값이 target에 덮어씌여짐.

그냥 복사하려면 빈객체를 생성하여 복하하면 됨.

참고 : developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/assign