본문 바로가기
💻CODING/javascript

[js] 객체를 배열로 바꾸는 법, 배열을 객체로 바꾸는 법

by 코딩하는 갓디노 2021. 6. 25.

객체를 배열로, 배열을 객체로

 

자바스크립트 데이터에서 
객체를 배열로,
배열을 객체로 바꾸는 방법입니다.

 

실무에서는 화면에서 게시판, 테이블과 같은 형태의 출력을 위해,
또는 서버 전송을 위해 자주 객체를 배열로 변환하게 됩니다.
객체를 배열로 변환하는 방법을 알아보겠습니다.

 

객체를 배열로 바꾸는 법

Object.entries()

 

객체를 배열로 바꾸는 예제

let fruit = {
  color: "yellow",
  name: "banana",
  taste: 'good',
  location: 3
}
console.log(Object.entries(fruit))
//결과 - 2차원 배열이 리턴됨
(4)[Array(2), Array(2), Array(2), Array(2)]
0: (2)["color", "yellow"]
1: (2)["name", "banana"]
2: (2)["taste", "good"]
3: (2)["location", 3]

 

배열을 객체로 바꾸는 법

  • Object.assign(target, source)
  • Target: 대상 객체 / Source: 하나 이상의 출처 객체
  • Target(첫번째 인수) 객체에다가 source(두번째 인수)를 병합합니다.
  •  즉, target에 source의 소스를 복사하여 병합이 되어 target을 반환합니다.
Object.assign({}, array)

 

배열을 객체로 바꾸는 예제

let fruit = [
  {color: "yellow"},
  {name: "banana"},
  {taste: 'good'},
  {location: 3}
]

console.log(Object.assign({}, fruit));
//결과
{0: {…}, 1: {…}, 2: {…}, 3: {…}}
0: {color: "yellow"}
1: {name: "banana"}
2: {taste: "good"}
3: {location: 3}
__proto__: Object

 

서로 다른 두 개의 객체 데이터를 하나의 객체로 만들기

원본 데이터는 손상하지 않고, 두 객체의 속성을 합쳐 새로운 객체를 반환합니다.
여기서 중복되는 키는 속성의 경우는 나중의 속성 한개만 반환됩니다

Object.assign({}, source1, source2)

 

두개의 서로 다른 객체 데이터를 하나로 합치는 예제

let fruit1 = {
  color: "yellow", //중복 키
  name: "banana"
}

let fruit2 = {
  name: "apple", //중복 키
  taste: "good",
  location: 3
}

const target = Object.assign({}, fruit1, fruit2);
console.log(target);
//결과
{color: "yellow", name: "apple", taste: "good", location: 3}

 

객체의 속성 값만 모아서 배열로 만들기 

Object.keys()

 

객체의 속성만 모아서 새로운 배열로 만들기 예제

let fruit = {
  color: "yellow",
  name: "banana",
  taste: "good",
  location: 3
}

const target = Object.keys(fruit);
console.log(target);
//결과
(4) ["color", "name", "taste", "location"]

 

객체의  value만 모아서 배열로 만들기 

Object.values()

 

객체의 값만 모아서 새로운 배열로 만들기 예제

let fruit = {
  color: "yellow",
  name: "banana",
  taste: "good",
  location: 3
}

const target = Object.values(fruit);
console.log(target);
//결과
(4) ["yellow", "banana", "good", 3]
반응형

댓글