JS中將對象轉化為數組


一、通過for循環把一個對象變為 1 個數組

   let obj = {
      name: 'aaa',
      height: 190,
      sex: 'man',
    };
    let objNew = [];
    for (let i in obj) {
      objNew.push({ [i]: obj[i] })
    }
    console.log('objNew',objNew);
      let test = {
        livenessDetection: {
          amout: [1, 2, 3, 4, 5, 5],
          num: [2.3, 4.5, 2, 6, 2, 1]
        },
        lives: {
          amout: [1, 2, 3, 4, 5, 5],
          num: [2.3, 4.5, 2, 6, 2, 1]
        }
      };
      let newArr = [];
      for (let j in test) {
        console.log('j',j);
        console.log('test[j]', test[j]);
        newArr.push({ [j]: test[j] })
      }
      console.log(newArr);
 

二、通過for循環把一個對象變為 2 個數組(得到對象的key的集合或者value的集合)

     let amout = {
        '2021-10-02': 0,
        '2021-10-02': 0,
        '2021-10-03': 0,
        '2021-10-04': 0,
        '2021-10-05': 0,
        '2021-10-06': 0,
        '2021-10-07': 0,
        '2021-10-08': 2.2,
        '2021-10-09': 2.5,
        '2021-10-10': 0,
        '2021-10-11': 0,
        '2021-10-12': 0,
        '2021-10-13': 0,
        '2021-10-14': 0,
        '2021-10-15': 0,
        '2021-10-16': 0,
        '2021-10-17': 0
      };
      let arr = [];
      let arr2 = [];
      for (let j in amout) {
        arr.push(j);
        arr2.push(amout[j]);
      }
      console.log(arr);
      console.log(arr2);

//['2021-10-02', '2021-10-03', '2021-10-04', '2021-10-05', '2021-10-06', '2021-10-07', '2021-10-08', '2021-10-09',
'2021-10-10', '2021-10-11', '2021-10-12', '2021-10-13', '2021-10-14', '2021-10-15', '2021-10-16', '2021-10-17']
//[0, 0, 0, 0, 0, 0, 2.2, 2.5, 0, 0, 0, 0, 0, 0, 0, 0]

上面數組也可能通過Object.keys()獲取自身屬性,Object.keys返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵名。

Object.keys(amout);

通過Object.values()獲取鍵值。Object.values方法返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值。

Object.values(amout);

 

參考地址:https://www.jianshu.com/p/3d823b9d632b


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM