0
0

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 3 years have passed since last update.

JavaScriptの連想配列の配列で特定のvalueが配列の何番目(index)で出現するかを知る

Last updated at Posted at 2021-02-15

例えば、'school'が何番目のオブジェクトの中にあるのか知りたい場合。

const genres = [
    {route: 'jobs', name: '仕事'},
    {route: 'life', name: '日常'},
    {route: 'relationship', name: '人間関係'},
    {route: 'dozi', name: 'どじ'},
    {route: 'shame', name: '恥かいた'},
    {route: 'school', name: '学校'},
    {route: 'love', name: '恋愛'},
    {route: 'marriage', name: '結婚生活'},
    {route: 'game', name: 'ゲーム'},
    {route: 'disease', name: '病気'},
    {route: 'heart', name: ''},
];

//まずrouteのvalueだけで配列を作成する。
const genreRoutes = genres.map((obj) => {
  return obj.route;
});
// 結果 genreRoutes = ['jobs', 'life', 'relationship', ....]

let index = genreRoutes.indexOf('school');
// 結果 5

なんか日本語が難しいですね。
タイトルがわけわかめ。。
ほぼ自分用なのですみません。

ちなみになぜ'route'なのかというと、Vue Routerでルートパラメータとして使用するからです。
もしこれ以外に方法があれば教えてくださいm(__)m

0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?