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"
메소드는 주어진 객체의 속성 이름, 값들을 일반적인 반복문과 동일한 순서로 순회되는 열거 할 수 있는 배열로 반환
(for...in 구문과 동일한 순서를 가진다)
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
const object2 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.values(object2));
// expected output: Array ["somestring", 42, false]
기준 문자열과 비교했을 때 비교 대상 문자열이 정렬상 전에 오는지, 후에 오는지 혹은 같은 순서에 알려주는지 숫자 리턴
// The letter "a" is before "c" yielding a negative value
'a'.localeCompare('c'); // -2 or -1 (or some other negative value)
// Alphabetically the word "check" comes after "against" yielding a positive value
'check'.localeCompare('against'); // 2 or 1 (or some other positive value)
// "a" and "a" are equivalent yielding a neutral value of zero
'a'.localeCompare('a'); // 0