2016-10-26 3 views
0

私はデータ構造の中に深いところにあるオブジェクトを見つけるのに役立つと思って次の関数を書きました。しかし、これはforeach内でスコープされているリターンのために動作しません。この関数は常にundefinedを返します。私はこれをどのようにしなければならないのですか?forEachから戻って

const findStuff = (data, x) => { 
    data.forEach(u => { 
     u.userData.forEach(ud => { 
      const s = ud.stuff.find(s=>s.id === x.id); 
      if (s){ 
       return s; 
      } 
     }); 
    }); 
}; 
+1

通常の 'for'を使用してそれを返します。 – tymeJV

+0

' .find() 'を使用しますか? – vlaz

+0

そうだとは思わなかった。 So-o-o、あなたの '.forEach'を' .map'のために入れ替えてください – vlaz

答えて

1

あなたのアプローチは間違っていると思います。それは多くのコードに...です。あなたは、単一のアイテムを取得したいので、

var data = [ 
 
    { 
 
    username: "Alice", 
 
    userData : [ 
 
     { 
 
     id: 1, 
 
     someData: "hello" 
 
     }, 
 
     { 
 
     id: 2, 
 
     someData: "world" 
 
     } 
 
    ] 
 
    }, 
 
    { 
 
    username: "Bob", 
 
    userData : [ 
 
     { 
 
     id: 3, 
 
     someData: "apple" 
 
     }, 
 
     { 
 
     id: 4, 
 
     someData: "orange" 
 
     } 
 
    ] 
 
    } 
 
]; 
 

 
const findStuff = (data, lookup) => { 
 
    return data.find(
 
    item => item.userData.some(
 
     userDataItem => userDataItem.id === lookup.id 
 
    ) 
 
); 
 
} 
 

 
const shouldGetAlice  = findStuff(data, {id: 1}); 
 
const shouldBeAliceAgain = findStuff(data, {id: 2}); 
 
const shouldGetBob  = findStuff(data, {id: 3}); 
 
const shouldBeAnotherBob = findStuff(data, {id: 4}); 
 

 
console.log(shouldGetAlice.username); 
 
console.log(shouldBeAliceAgain.username); 
 
console.log(shouldGetBob.username); 
 
console.log(shouldBeAnotherBob.username);

.find()でオフに開始します。私はあなたを介して探しているデータに適合するように思われるオブジェクトを作りました。

コールバックでは、.some()を使用して、userDataのプロパティをループしないで確認します。

これだけです。各アレイを手動でループする必要はありません。わかりやすい変数名が削除される場合

、機能はまた、1行に書き込むことができますが、それはあまり明確思わ

const findStuff = (data, x) => { 
    return data.find(u => u.userData.some(ud => ud.id === x.id)); 
} 

に短縮することができます。

0

クロージャーの上部にある変数を使用し、forEachの後にそれを返します。

const findStuff = (data, x) => { 
    let found; 

    data.forEach(u => { 
     u.userData.forEach(ud => { 
      const s = ud.stuff.find(s=>s.id === x.id); 
      if (s){ 
       found = s; 
      } 
     }); 
    }); 

    return found; 
}; 
0

あなたはArray#someを使用することができますし、trueを返すと繰り返しを終了します。見つかった値には変数が必要です。

const findStuff = (data, x) => { 
    let found; 

    data.some(u => 
     u.userData.some(ud => { 
      const s = ud.stuff.find(s => s.id === x.id); 
      if (s) { 
       found = s; 
       return true; 
      } 
     }) 
    ); 
    return found; 
}; 
関連する問題