2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavaScript】オブジェクトの同じ階層の別のキーの値を取得する【json】

Last updated at Posted at 2022-06-22

課題

以下のようなオブジェクトがあるとします。

const obj = {
  "data": [
    {
      "first_name": "田中",
      "last_name": "太郎"
    },
    {
      "first_name": "鈴木",
      "last_name": "次郎"
    },
    {
      "first_name": "佐藤",
      "last_name": "三郎"
    }
  ]
}

オブジェクトの同じ階層の別のキーの値を取得したい。
例えば、田中という値から、太郎という値を取得

解決方法

const keyword = "田中"
const result = obj.data.filter(x=>x.first_name==keyword).map(x=>x.last_name)[0]??null;
console.log(result);
// 太郎

一般化 & 関数化する


const find = (data, keyword, key1, key2) => {
  return data.filter(x=>x[key1]==keyword).map(x=>x[key2])[0]??null;
}

find(obj.data, "田中", "first_name", "last_name")
// 太郎
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?