LoginSignup
1
1

More than 3 years have passed since last update.

【JavaScript】JSONを検索して、特定のデータを取り出す方法

Last updated at Posted at 2020-02-26

まずはJSONデータを用意

とりあえずこんな感じで用意しました。

const JSONDATA = [
  {
    id: "aaa",
    name: "apple"
  },
  {
    id: "bbb",
    name: "orange"
  },
  {
    id: "ccc",
    name: "grape"
  }
];

idを指定してオレンジを取り出す!

「findIndex」を使って何番目かを確認し(0はじまり)、その番号を指定してJSONデータを返します。

const getFruitById = id => {
    const fruitIndex = JSONDATA.findIndex(data => data.id === id);
    return JSONDATA[fruitIndex];
};

const orange =  getFruitById("bbb");
console.log(orange.name); // display orange

1
1
3

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
1
1