2024年8月27日 星期二

V80202 -Object.Keys() -Object.Values() -Object.entries() - Object2Array:Object.entries(Obj) - Array2Object: Object.fromEntries(Ary)

  目的:  Object 轉成 Array , Array 轉成Object

處理說明:  1>Object 轉成 Array  - Object.entries(obj);
                         const obj = { name: 'Luke Skywalker', title: 'Jedi Knight', age: 23 };
                         const Ary = Object.entries(obj);

                  2>Array 轉  Object  - Object.fromEntries(Ary);
                      const  Ary_filtered = Ary.filter(  ([key, value]) => typeof value === 'string');
                     const  obj_str = Object.fromEntries(Ary_filtered);

                3>Sample:
                     const Obj_num = { 'BUF': 11, 'MIA': 9, 'NE': 6, 'NYJ': 1 };
                     const Ary_num= Object.entries(Obj_num );
                     Ary_num.filter( function(key,value){ return value>=9; } ); //正式函式寫法
                     Ary_num.filter( ([key,value]) => value>=9; ); //另一寫法
                    const Obj_num9=Object.fromEntries(Ary_num);

               4>Object  - for  (key in Obj) {}
                  let rectangle = {width: 16, height: 9}; 
                  for (const key in rectangle) 
                    { console.log(key, rectangle[key]); } 
                  -->  // width 16 // height 9
               5>Object.keys() : 傳回  Array of  Keys
                   let obj = {a: 1, b: 2, c: 3}; 
                  console.log(Object.keys(obj)); // ["a", "b", "c"]
               6>Object.Values() : 傳回  Array of  Values
                   console.log(Object.values(obj)); // [1, 2, 3]
              7>Object.entries()直接取得所有 property 的 name 和 value,並以陣列回傳
                   console.log(Object.entries(object)); // [
                                                                                      ["a",1],
                                                                                      ["b",2],
                                                                                      ["c",3],
                                                                                  ]      

沒有留言:

張貼留言