Object.keys()
메소드는 주어진 객체의 속성 이름들을 일반적인 반복문과 동일한 순서로 순회되는 열거할 수 있는 배열로 반환한다.
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
Object.values()
메소드는 전달된 파라미터 객체가 가지는 (열거 가능한) 속성의 값들로 이루어진 배열을 리턴한다.
이 배열은 for...in
구문과 동일한 순서를 가진다. (for in 반복문은 프로토타입 체인 또한 열거한다는 점에서 차이가 있다)
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]
Object.entries()
메서드는 for...in
와 같은 순서로 주어진 객체 자체의 enumerable 속성 [key, value]
쌍의 배열을 반환한다. (for-in
루프가 다른점은 프로토 타입 체인의 속성도 열거한다는 점)
Object.entries()
에 의해 반환된 배열(array)의 순서는 객체가 정의된 방법과 관련이 없다.
배열 순서가 쓸 곳이 있다면, 다음과 같이 정렬을 먼저 해야한다. Object.entries(obj).sort((a, b) => b[0].localeCompare(a[0]));
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
ex)
const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
// array like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
// array like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]