Saya memiliki array objek. Saya mencoba membuat array objek seperti matriks.

Ini kode saya:

let data = [
    {device: 'iphone',   site: 'google', val1:10, val2:20, val3:30},
    {device: 'iphone',   site: 'bing',   val1:23, val2:12, val3:14},
    {device: 'iphone',   site: 'jeeves', val1:67, val2:78, val3:12},
    {device: 'ipad',     site: 'google', val1:10, val2:20, val3:30},
    {device: 'ipad',     site: 'bing',   val1:23, val2:12, val3:14},
    {device: 'ipad',     site: 'jeeves', val1:67, val2:78, val3:12}
    ];

let arr = data.map(d => Object.values(d));
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ketika saya melakukan peta seperti di atas, saya memasukkan semua nilai objek ke dalam array array.

Bagaimana cara membuat data saya terlihat seperti ini:

    arr = [
        [0,0,67], [0,1,23],[0,2,10],[0,3,67],[0,4,23],[0,5,10],
        [1,0,78], [1,1,12],[1,2,20],[1,3,78],[1,4,12],[1,5,20],
        [2,0,12], [2,1,14],[2,2,30],[2,3,12],[2,4,14],[2,5,30],
        ]

Tidak yakin bagaimana membuat objek array saya terlihat seperti matriks di atas.

0
nb_nb_nb 28 Mei 2021, 17:00

1 menjawab

Jawaban Terbaik

Untuk mendapatkan nilai numerik saja dari setiap objek gunakan Array.filter(), dan abaikan nilai yang NaN (bukan angka):

const data = [{"device":"iphone","site":"google","val1":10,"val2":20,"val3":30},{"device":"iphone","site":"bing","val1":23,"val2":12,"val3":14},{"device":"iphone","site":"jeeves","val1":67,"val2":78,"val3":12},{"device":"ipad","site":"google","val1":10,"val2":20,"val3":30},{"device":"ipad","site":"bing","val1":23,"val2":12,"val3":14},{"device":"ipad","site":"jeeves","val1":67,"val2":78,"val3":12}];

const arr = data.map(d => Object.values(d).filter(v => !isNaN(v)));

console.log(arr);

Untuk mendapatkan matriks Anda - balikkan larik, petakan objek, lalu petakan nilainya setelah memfilternya, dan gunakan indeks. Ratakan hasil satu tingkat, dan urutkan sesuai dengan nilai ke-1 dari setiap sub-array dalam matriks.

const data = [{"device":"iphone","site":"google","val1":10,"val2":20,"val3":30},{"device":"iphone","site":"bing","val1":23,"val2":12,"val3":14},{"device":"iphone","site":"jeeves","val1":67,"val2":78,"val3":12},{"device":"ipad","site":"google","val1":10,"val2":20,"val3":30},{"device":"ipad","site":"bing","val1":23,"val2":12,"val3":14},{"device":"ipad","site":"jeeves","val1":67,"val2":78,"val3":12}];

const arr = [...data]
  .reverse()
  .map((d, y) => 
    Object.values(d)
      .filter(v => !isNaN(v))
      .map((v, x) => [x, y, v])
  )
  .flat(1)
  .sort(([a], [b]) => a - b);
  
console.log(arr);
4
Ori Drori 28 Mei 2021, 14:31