javascript オブジェクトのプロパティをflatに取得する

javascript オブジェクトのプロパティをflatに取得する

javascriptで、オブジェクトのプロパティをflatに取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

flatに取得

例えば、以下のようなオブジェクトの「attributes」をflatに取得する場合は、「flatMap」を使用することで可能です。

[
    { username: 'Tanaka', attributes: ['a', 'b'] },
    { username: 'Suzuki', attributes: ['c'] },
]

「flatMap」を使用します。

'use strict';

console.log( 
  [
    { username: 'Tanaka', attributes: ['a', 'b'] },
    { username: 'Suzuki', attributes: ['c'] },
  ].flatMap(x => x.attributes)
);

実行結果を確認すると、「attributes」が1つの配列として「flat」に取得されていることが確認できます。

サンプルコード

以下は、
「実行」ボタンをクリックして、オブジェクのプロパティをflatして表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = () => {
    
    const arr = [
      { username: 'Tanaka', attributes: ['a', 'b'] },
      { username: 'Suzuki', attributes: ['c'] },
    ].flatMap(x => x.attributes)

    // disp関数を実行
    disp(arr, "list");

  }

  //フロントに表示する関数
  const disp = (arr, id) => {

    let text = [];    

    arr.forEach((x, i) => text.push('<li class="list-group-item">' + arr[i] + '</li>'))
    
    document.getElementById(id).innerHTML = text.join('');

  }

  window.onload = () => {

    btn.onclick = () => { hoge() };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <ul id="list" class="font-semibold text-lg mr-auto"></ul>

      <button id="btn"
        class="mb-2 md:mb-0 bg-red-400 px-5 py-2 text-sm shadow-sm font-medium tracking-wider text-white rounded-full hover:shadow-lg hover:bg-red-500">
        実行
      </button>
    </div>

  </div>
</body>

</html>

実行結果を確認すると、オブジェクトの「attributes」が表示されていることが確認できます。