javascript オブジェクトの最後の値を取得する

javascript オブジェクトの最後の値を取得する

javascriptで、オブジェクトの最後の値を取得するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

オブジェクトの最後の値を取得

オブジェクトの最後の値を取得するには「keys」でキーを「value」で値を取得して「pop」を使用します。

const obj = {one: 1, two: 2, three: 3};

const key = Object.keys(obj).pop();
console.log(key); 
// three

const value = Object.values(obj).pop();
console.log(value); 
// 3

let lastObj = {};

lastObj[key] = value;

console.log(lastObj); 
// {three: 3}

console.log({[key]:value}); 
// {three: 3}

console.log(obj);
// {one: 1, two: 2, three: 3}

「Object.entries」を使用すると配列で取得することができます。

const obj = {one: 1, two: 2, three: 3};

const arr = Object.entries(obj).pop();
console.log(arr); 
// ['three', 3]

console.log(obj);
// {one: 1, two: 2, three: 3}

サンプルコード

以下は、
「取得」ボタンをクリックすると、用意したオブジェクトから最後の値を取得して表示する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-75 mx-auto" style="margin-top:200px">

    <h2><span class="badge badge-info"></span></h2>
    <h2><span class="badge badge-info">最後のオブジェクト</span></h2>

    <button type="button" onclick="hoge()" class="btn btn-raised btn-info">
      取得
    </button>

  </div>

  <script>

    let obj = { one: 1, two: 2, three: 3 };

    // 表示用要素取得
    let elm = document.getElementsByClassName("badge")[0];

    // JSON 文字列に変換して表示
    elm.textContent = JSON.stringify(obj);

    const hoge = () => {

      // 表示用要素取得
      let elm = document.getElementsByClassName("badge")[1];

      const key = Object.keys(obj).pop();
      console.log(key);
      // three

      const value = Object.values(obj).pop();
      console.log(value);
      // 3

      // JSON 文字列に変換して表示
      elm.textContent = JSON.stringify({[key]:value});

    }

  </script>
</body>

</html>

取得されていることが確認できます。