オブジェクトのループ
キーと値の両方
const obj = { name: 'john', age: 10, address: 'us' };
for (const [key, val] of Object.entries(obj)) {
console.log(key, val);
}
キーだけ
const obj = { name: 'john', age: 10, address: 'us' };
for (const key of Object.keys(obj)) {
console.log(key);
}
値だけ
const obj = { name: 'john', age: 10, address: 'us' };
for (const val of Object.values(obj)) {
console.log(val);
}
空オブジェクトの判定
const obj = {};
console.log(Object.entries(obj).length === 0);
console.log(Object.keys(obj).length === 0);
console.log(Object.values(obj).length === 0);
変換
const users = { Alice: 3, Bob: 1, Carol: 2 };
const users2 = Object.entries(users)
.reduce((obj, [key, val]) => {
obj[key] = val * 2;
return obj;
}, {});
// users2 = { Alice: 6, Bob: 2, Carol: 4 }