LoginSignup
0
0

More than 1 year has passed since last update.

JavaScript 配列の中のオブジェクトの要素を一つ一つ取り出して判定する

Posted at

概要

  • 配列の中のオブジェクトの要素を一つ一つ取り出して判定する方法をまとめる。

やりたい事

  • 下記のような配列があったとする。

    let data = [
      {
        'id': 'null',
        'rent': '100',
        'name': 'A'
      },
      {
        'id': '1',
        'rent': '200',
        'name': 'B'
      },
      {
        'id': '2',
        'rent': '300',
        'name': 'C'
      }
    ];
    
  • 各オブジェクトのidが「null」という文字列のオブジェクトをid_nullの配列に、idが「null」という文字列以外のオブジェクトをid_unnullの配列に分けたい。

方法

  • filter()メソッドを使って下記の様に記載することで実現できる。

    let data = [
      {
        'id': 'null',
        'rent': '100',
        'name': 'A'
      },
      {
        'id': '1',
        'rent': '200',
        'name': 'B'
      },
      {
        'id': '2',
        'rent': '300',
        'name': 'C'
      }
    ];
    
    let id_null = data.filter(function(datum) {
        return datum.id === 'null';
    })
    
    let id_unnull= data.filter(function(datum) {
        return datum.id !== 'null';
    })
    
    console.log(id_null);
    console.log(id_unnull)
    
  • 下記の様に出力される。

    [ { id: 'null', rent: '100', name: 'A' } ]
    [
      { id: '1', rent: '200', name: 'B' },
      { id: '2', rent: '300', name: 'C' }
    ]
    

簡単な解説

  • filter()メソッドの引数に無名関数を与え、その無名関数がtrueを返した時、当該のオブジェクトを返す。

参考文献

0
0
0

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