#author("2021-07-08T18:17:55+09:00","default:ryuichi","ryuichi")
#author("2021-07-08T18:18:20+09:00","default:ryuichi","ryuichi")
* オブジェクトのループ [#w33e8c54]

** キーと値の両方 [#ecaab23d]

#pr(javascript){{
 const obj = { name: 'john', age: 10, address: 'us' };
 for (const [key, val] of Object.entries(obj)) {
   console.log(key, val);
 }
}}


** キーだけ [#v9e491d4]

#pr(javascript){{
 const obj = { name: 'john', age: 10, address: 'us' };
 for (const key of Object.keys(obj)) {
   console.log(key);
 }
}}

** 値だけ [#j92b9417]

#pr(javascript){{
 const obj = { name: 'john', age: 10, address: 'us' };
 for (const val of Object.values(obj)) {
   console.log(val);
 }
}}

** 空オブジェクトの判定 [#ofc6cc32]

#pr(javascript){{
 const obj = {};
 console.log(Object.entries(obj).length === 0);
 console.log(Object.keys(obj).length === 0);
 console.log(Object.values(obj).length === 0);
}}

** 変換 [#c1cf9272]

#pr(javascript){{
const users = { Alice: 3, Bob: 1, Carol: 2 };
const users2 = Object.entries(users)
  .reduce((obj, [key, val]) => {
    obj[key] = val * 2;
    return obj;
  }, {});

// { Alice: 6, Bob: 2, Carol: 4 }
// users2 = { Alice: 6, Bob: 2, Carol: 4 }
}}

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS