2016-10-06 15 views
2

'Item-1-5-2'という値を持つ 'text'フィールドなど、配列内のアイテムを再帰的に見つけるためのlodashで最も簡単な解決策は何でしょうか?lodashは再帰的に配列内のアイテムを見つける

const data = [ 
     { 
     id: 1, 
     text: 'Item-1', 
     children: [ 
      { id: 11, text: 'Item-1-1' }, 
      { id: 12, text: 'Item-1-2' }, 
      { id: 13, text: 'Item-1-3' }, 
      { id: 14, text: 'Item-1-4' }, 
      { 
      id: 15, 
      text: 'Item-1-5', 
      children: [ 
       { id: 151, text: 'Item-1-5-1' }, 
       { id: 152, text: 'Item-1-5-2' }, 
       { id: 153, text: 'Item-1-5-3' }, 
      ] 
      }, 
     ] 
     }, 
     { 
     id: 2, 
     text: 'Item-2', 
     children: [ 
      { id: 21, text: 'Item-2-1' }, 
      { id: 22, text: 'Item-2-2' }, 
      { id: 23, text: 'Item-2-3' }, 
      { id: 24, text: 'Item-2-4' }, 
      { id: 25, text: 'Item-2-5' }, 
     ] 
     }, 
     { id: 3, text: 'Item-3' }, 
     { id: 4, text: 'Item-4' }, 
     { id: 5, text: 'Item-5' }, 
    ]; 

ありがとうございます!

答えて

2

普通のJavaScriptでは、Array#someを再帰的に使用できます。

function getObject(array, key, value) { 
 
    var o; 
 
    array.some(function iter(a) { 
 
     if (a[key] === value) { 
 
      o = a; 
 
      return true; 
 
     } 
 
     return Array.isArray(a.children) && a.children.some(iter); 
 
    }); 
 
    return o; 
 
} 
 

 
var data = [{ id: 1, text: 'Item-1', children: [{ id: 11, text: 'Item-1-1' }, { id: 12, text: 'Item-1-2' }, { id: 13, text: 'Item-1-3' }, { id: 14, text: 'Item-1-4' }, { id: 15, text: 'Item-1-5', children: [{ id: 151, text: 'Item-1-5-1' }, { id: 152, text: 'Item-1-5-2' }, { id: 153, text: 'Item-1-5-3' }, ] }, ] }, { id: 2, text: 'Item-2', children: [{ id: 21, text: 'Item-2-1' }, { id: 22, text: 'Item-2-2' }, { id: 23, text: 'Item-2-3' }, { id: 24, text: 'Item-2-4' }, { id: 25, text: 'Item-2-5' }, ] }, { id: 3, text: 'Item-3' }, { id: 4, text: 'Item-4' }, { id: 5, text: 'Item-5' }, ]; 
 

 
console.log(getObject(data, 'text', 'Item-1-5-2'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

これは、再帰関数のための最適なスポットです。

function findText(items, text) { 
    if (!items) { return; } 

    for (const item of items) { 
    // Test current object 
    if (item.text === text) { return item; } 

    // Test children recursively 
    const child = findText(item.children, text); 
    if (child) { return child; } 
    } 
} 

これは、最大のパフォーマンスを得るための最良の方法です。トラバーサルは深みのあるもので最初の検索方法です。

関連する問題