Array.from Object.keys Object.values Object.entries

lee jae hwan·2022년 7월 23일

javascript

목록 보기
19/107

Array.from()
유사배열객체나 이터러블객체를 얕게 복사해 배열객체를 만든다.
유사배열도 아니고 이터러블도 아닌 일반객체를 배열로 만들수는 없다.

Array.from(arrayLike[, mapFn[, thisArg]])

Array.from('foo'); // ["f", "o", "o"]
Array.from([1, 2, 3], x => x + x); // [2, 4, 6]



아래 메소드들은 유사배열도 아니고 이터러블도 아닌 일반객체로부터 배열을 추출할 수 있다.

Object.keys()
객체의 열거가능한 속성이름들을 배열로 반환

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};
console.log(Object.keys(object1)); //  ["a", "b", "c"]

Object.values()
객체의 열거가능한 속성값들로 이루어진 배열을 반환
이 배열은 for...in 구문과 동일한 순서를 가진다.

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};
console.log(Object.values(object1)); //  ["somestring", 42, false]

Object.entries()
객체의 열거가능한 속성 이름과 값의 쌍을 배열을 반환

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

Object.entries로 반환된 배열의 원소또한 ['a','somestring']와 같은 배열이기때문에 반복순회시 배열구조분해하면 된다.

0개의 댓글