본문 바로가기

Web/JavaScript&JQuery

[Javascript]Array, Object, JSON구분 정리

안녕하세요 미나라이입니다.

 

자바스크립트를 하면서 위 3가지를 자주 사용하기 때문에 정리를 해 보았습니다.

 

데이터 형태

 

문법

Array

1. 배열 > 문자열 변환

const fruits = ["Banana", "Orange", "Apple", "Mango"];	
fruits.toString()	
// 출력 결과
Banana,Orange,Apple,Mango

2. 문자로 출력하되 구분점을 바꾸고 싶은 경우

const fruits = ["Banana", "Orange", "Apple", "Mango"];	
fruits.join(" * ")	
//출력결과
Banana * Orange * Apple * Mango

3. 배열 정렬하기

const fruits = ["Banana", "Orange", "Apple", "Mango"];		
//오름차순
fruits.sort(); 	
//내림차순
fruits.reverse();

4. 숫자배열 정렬하기

const points = [40, 100, 1, 5, 25, 10];		
//오름차순
points.sort(function(a, b){return a - b});	
//내림차순
points.sort(function(a, b){return b - a});

5. Array > JSON변환

const arr = ["John", "Peter", "Sally", "Jane"];		
const myJSON = JSON.stringify(arr);		
myJSON
//출력결과
["John","Peter","Sally","Jane"]

 

Object

1. 기본 출력 방법

const person = {		
  name: "John",		
  age: 30,		
  city: "New York"		
};

//Object명.Key로 출력
person.name + "," + person.age + "," + person.city;
//Object명["key"]로 출력
obj["name"] + ", " + obj["age"]	+ ", " + obj["city"]

2. 반복문 출력 방법

for (let x in person) {	
	// Key출력	
 	key = x; 
	// Value출력	
	value = person[x]";
};

3. Value만 전부 출력하는 방법

Object.values(person)		
//출력결과
John,30,New York

//JSON.parse(person)후에 Object.Values(person)을 하면 값이 이상해진다.		
//출력결과
{,",n,a,m,e,",:,",J,o,h,n,",,, ,",a,g,e,",:,3,0,,, ,",c,a,r,",:,n,u,l,l,}

4. Object객체 만들기

function Person(first, last, age, eye) {	
    this.firstName = first;	
    this.lastName = last;	
    this.age = age;	
    this.eyeColor = eye;	
}	

//만들어진 객체에 데이터 넣기		
const myFather = new Person("John", "Doe", 50, "blue");

5. Object > JSON 변환

const obj = {name: "John", age: 30, city: "New York"};		
const myJSON = JSON.stringify(obj);		
myJSON	
//출력결과
{"name":"John","age":30,"city":"New York"}

 

JSON

1. JSON각종 형태

2. JSON > Object 변환

const txt = '{"name":"John", "age":30, "city":"New York"}';	
const obj = JSON.parse(txt);

3. JSON > Array 변환 (Obejct와 동일)

const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';	
const myArr = JSON.parse(text);	
myArr[0];
//출력결과
Ford

 

복수 형태의 데이터 변환

1. Object안에 Array가 있는 경우

const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';		
const myObj = JSON.parse(myJSON);		
myObj.cars[0];	
//출력결과
Ford	

// 반복출력		
for (let i in myObj.cars) {		
  text += myObj.cars[i] + ", ";		
}		
//출력결과
Ford, BMW, Fiat,

2. Array안에 JSON데이터가 있는 경우

const restaurants = 	
[	
    {	
        "location" : "123 Road Dr", 	
        "city_state" : "MyCity ST", 	
        "phone" : "555-555-5555", 	
        "distance" : "1" 	
    },	
    {	
        "location" : "456 Avenue Crt", 	
        "city_state" : "MyTown AL", 	
        "phone" : "555-867-5309", 	
        "distance" : "0" 	
    }	
];	

restaurants[0].location;
// 출력결과
123 Road Dr

3. 기타 복수 형태의 데이터 출력 방법

const txt =  {
               "menu":{
                  "name":"file",
                  "age":"File",
                  "popup":{
                     "menuitem":[
                        {
                           "value":"New",
                           "onclick":"CreateNewDoc()"
                        },
                        {
                           "value":"Open",
                           "onclick":"OpenDoc()"
                        },
                        {
                           "value":"Close",
                           "onclick":"CloseDoc()"
                        }
                     ]
                  }
               }
            };

const obj = JSON.parse(txt);		
obj.menu.popup.menuitem[0].value;	

// 출력결과
New

※ JSON.parse를 사용하면 내부 속성까지 한번에 parse해줍니다.

 

이상으로 간단하게 정리를 마치겠습니다.

 

참고 링크

 

JavaScript Tutorial

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

728x90
반응형