LoginSignup
1
0

More than 3 years have passed since last update.

【JavaScript】mapでオブジェクトの配列の中身を確認する

Last updated at Posted at 2020-04-28

やりたいこと

オブジェクトの配列objectArrayの中に、color = 'blue'なオブジェクトが存在するかを(シュッとした感じで)判定したい。

const objectArray= [{color: 'red', type: 'soft'}, 
                    {color: 'blue', type: 'hard'},
                    {color: 'pink', type: 'soft'}, 
                    {color: 'black', type: 'hard'}]

文字列の配列ならincludesで判定できますが、オブジェクトの配列だとうまくいきません。

const stringArray = ['blue', 'red', 'pink', 'pink']

console.log(stringArray.includes('blue'))
// expected output: true

console.log(objectArray.includes('blue'))
// false になってしまう

どうする

はじめにmapを使って文字列の配列にし、そのあとでincludesで判定します。

console.log(objectArray.map(x => x.color).includes('blue'))
// expected output: true

これで判定ができました。(シュッとしてるね!)
@sdkei さんにコメントいただいた書き方のほうが良いので追記しました。→ 追記その2

おまけ

blueは何番目にあるのか?を知りたい場合もある(というか、こっちのほうが多い??)と思いますので、2つ紹介します。(2つ目はmap使ってないけど)

console.log(objectArray.map(x => x.color).indexOf('blue'))
// expected output: 1

console.log(objectArray.findIndex(({color}) => color == 'blue'))
// expected output: 1

colorに重複がある場合は一番小さいindexだけが出てくると思います。blueなオブジェクトのindexをすべて取得したい場合はこんな感じでしょうか。(シュッとしてませんが勘弁してください)

const objectArray2= [{color: 'red', type: 'soft'},
                     {color: 'blue', type: 'hard'},
                     {color: 'blue', type: 'soft'},
                     {color: 'pink', type: 'soft'},
                     {color: 'black', type: 'hard'}]

const result = objectArray2.map((val, itr) => val.color == 'blue' ? itr : -1).filter((x) => x != -1)
console.log(result)
// expected output: Array [1, 2]

@norkron さんにコメントいただいた書き方がシュッとしているので追記しました。→ 追記その1
@ttatsf さんにコメントいただいた書き方もシュッとしているので追記しました。→ 追記その3

以上、ご清聴ありがとうございました。
(どちらもmapを使わないほうが良いケースだったため、不適切なタイトルになっていますね。ゴメンナサイ。)

2020-04-28 追記その1

@norkron さんからコメントをいただきました。
filterを使わない、シュッとした書き方になっています。

const objectArray2= [{color: 'red', type: 'soft'}, 
                     {color: 'blue', type: 'hard'},
                     {color: 'blue', type: 'soft'},
                     {color: 'pink', type: 'soft'}, 
                     {color: 'black', type: 'hard'}]

const result = objectArray2.flatMap((val, itr) => val.color == 'blue' ? [itr] : [])
console.log(result)
// expected output: Array [1, 2]

2020-04-28 追記その2

@sdkeiさんからコメントをいただきました。
someを使った、より良い書き方です。(見た目も計算効率も良いです。)

console.log(objectArray.some(x => x.color === 'blue'));

2020-04-29 追記その3

@ttatsfさんからコメントをいただきました。
三項演算子とスプレッド構文を使ったシュッとした書き方です。

objectArray2.reduce((acc, obj, i)=> obj.color==='blue' ? [...acc, i] : acc, [] )
1
0
8

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
0