객체 선언 문법
var (객체이름) = {
(property1 이름) : property1값 ,
(property2 이름) : property2값
};
ex)
let andy = {
name : 'andy',
age : '24',
address : 'seoul'
}
주의 할 점으로는 property 의 이름은 중복해서는 안된다.
1. (객체이름).(property이름)
2. (객체이름)["(프로퍼티이름)"]
let plan1 = {
name : 'basic'
};
console.log(plan1.name);
console.log(plan1['name']);
basic
basic
언뜻 보면 1의 방법이 훨씬 편리하지만, 2의 방법을 써야 변수를 사용해서 프로퍼티의 값에 접근 할 수 있다.
let plan1 = {
name : 'basic'
};
const c = 'name';
console.log(plan1[c]);
basic
다음과 같은 활용도 가능하다.
let myObj = {
property1 : 'hello',
property2 : [1,2,3,4,5],
property3 : {
childproperty : 'haha'
}
};
let name = 'property';
console.log(myObj[name+'1']);
console.log(myObj[name+'2']);
console.log(myObj[name+'3']);
console.log(myObj[name+'3']['child'+name]); // myObj 객체안에 있는 '프로퍼티이자 객체'인 property3 의 'child'+name 프로퍼티 값을 가져옴
console.log(myObj.property1);
console.log(myObj.property2);
console.log(myObj.property3);
console.log(myObj.property3.childproperty);
'hello'
[ 1, 2, 3, 4, 5 ]
{ childproperty: 'haha' }
'haha'
'hello'
[ 1, 2, 3, 4, 5 ]
{ childproperty: 'haha' }
'haha'
접근 뿐 아니라 수정도 가능하다
let myObj = {
property1 : 'hello',
property2 : [1,2,3,4,5],
property3 : {
childproperty : 'haha'
}
};
let name = 'property1'
myObj[name] = ['hi', 'hello'];
console.log(myObj[name]);
[ 'hi', 'hello' ]
지금보면 string hello
이였던 property1 의 값을 배열 ['hi', 'hello']
로 바꾸었다.
즉 다음과 같이 접근이 가능해진다
console.log(myObj.property1[0]);
hello
let objData = {
name: 50,
address: {
email: "gaebal@gmail.com",
home: "위워크 선릉2호점"
},
books: {
year: [2019, 2018, 2006],
info: [{
name: "JS Guide",
price: 9000
}, {
name: "HTML Guide",
price: 19000,
author: "Kim, gae bal"
}]
}
};
다음과 같은 코드에서 HTML Guide 에 접근하고 싶을 때는 다음과 같이 하면 된다.
console.log(objData.books.info[1].name);