본문 바로가기

개발/JavaScript

[Javascript] 참조 타입 (Object Type)

생성

1. new, Object 이용

let person = new Object(); // let persoon = {} 과 동일
person.name = "dasom";
person.age = 20;
console.log(person);

2. 객체 리티럴 표기법 (선호함)

let person = {
    name : "dasom",
    age : 20,
    5 : true // 프로퍼티 이름에는 문자열이나 숫자를 쓸 수 있다 (숫자는 자동으로 문자로 바뀐다)
};
console.log(person);

 

사용

function displayInfo(args) {
    let output = "";
    
    if(typeof args.name === "string"){
        output += "Name : " + args.name + "\n";
    }
    
    if(typeof args.age === "number"){
        output += "age : " + args.age + "\n";
    }
    console.log(output);
}

displayInfo({ // 매개변수를 많이 쓸때 편리한 형태
    name : "dasom",
    age : 29
});

displayInfo({ 
    name : "yeajin" 
});

표기

점 표기법

console.log(person.name);

대괄호 표기법

console.log(person["name"]);

대괄호 표기법의 장점

변수를 써서 프로퍼티에 접근 할 수 있다.

const propertyName = "name"
console.log(person[propertyName])
console.log(person.propertyName) // undefined - 점 연산자는 불가능

 


JSON 이란?

  • JSON(Javascript Object Notation) : 데이터를 표시하는 포멧
  • Javascript 객체 문법으로 구조화된 데이터를 표현하기 위한 문자 기반의 표준 포멧

JSON의 구조

  • {key: value}
const data = {
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
              "Radiation resistance",
              "Turning tiny",
              "Radiation blast"
            ]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
              "Million tonne punch",
              "Damage resistance",
              "Superhuman reflexes"
      ]
    }
  ]
}

 

접근 예 

data.squadName  // Super hero squad
data['active']  // true
data['members'][1]['powers'][2]  // Superhuman reflexes
data['members'][0]  // {name: "Molecule Man", age: 29, secretIdentity: "Dan Jukes", powers: Array(3)}
data.powers  // undefined

 

Parsing(파싱) 이란?

  • 문자열에서 네이티브 객체로 변환하는 것
  • JSON.parse()? string -> json

Stringification(문자열화) 란?

  • 네트워크를 통해 전달할 수 있게 객체를 문자열로 변환하는 과정은 문자열화(Stringification)이라고 합니다
  • JSON.stringify()?  json  -> string

 

Json 추가/ 삭제 

const data = {
  Name: "DS",
  Age: "28"
}

// 추가
data.company = "kakao"
data.sex = "female"
console.log(data) // {Name: "DS", Age: "28", company: "kakao", sex: "female"}

// 삭제
delete data.sex;
console.log(data) // {Name: "DS", Age: "28", company: "kakao"}