[Day4] Looping Object - Javascript

ShiHoon Yoon·2020년 7월 22일
0

Before ES6

Object를 Loop하기 위해서 ES6전 버전에서는 for...in을 사용했다. 하지만 단점이 hasOwnProperty를 사용해서 실제로 property가 object에 포함되어있는지 확인을했어야했다.

for (var property in object) {
if (object.hasOwnProperty(property)) {
// Do things here
}
}

After ES6

Object를 Loop하기 더 좋은 방법은 먼저 Array로 변형 후 Loop하는 것이다.

Object.keys

const fruits = {
apple: 28,
orange: 17,
pear: 54,
}
const keys = Object.keys(fruits)
console.log(keys) // [apple, orange, pear]

Object.values

const fruits = {
apple: 28,
orange: 17,
pear: 54,
}
const values = Object.values(fruits)
console.log(values) // [28, 17, 54]

const fruits = {
apple: 28,
orange: 17,
pear: 54,
}
const entries = Object.entries(fruits)
console.log(entries)
// [
// [apple, 28],
// [orange, 17],
// [pear, 54]
// ]

Array로 변환 후

Object.keys, Object.values는

const keys = Object.keys(fruits)
for (const key of keys) {
console.log(key)
}
// Results:
// apple
// orange
// pear

Object.entries는 [key, property]로 분배해서

for (const [fruit, count] of entries) {
console.log(There are ${count} ${fruit}s)
}
// Result
// There are 28 apples
// There are 17 oranges
// There are 54 pears

profile
Entrepreneurs Should Learn to Code

0개의 댓글