2017-12-03 10 views
1

は3のシュッドを照会するランダムな名前を持つネストされたオブジェクトを照会 - lodash/javascriptの

Obj = 
{ 
    trees:{ 
    small:[1,2,3], 
    medium:[4,5,13], 
    large:[1,2,10] 
    }, 
    plants:{ 
    small1:[11,12,3], 
    medium1:[14,15,3], 
    large1:[11,12,10] 
    } 
} 

期待retulstsが

{ 
trees:{ 
    small:[1,2,3] 
    }, 
    plants:{ 
    small1:[11,12,3], 
    medium1:[14,15,3] 
    } 
} 

それでは、私も..一致する子が発見されたオブジェクトの親を取得する必要があります私は値

に一致するようにしようとしていた

function findInObjectsOfObjects(obj) { 
      console.log(obj) 
      for (var i in obj) { 
       console.log(obj[i]) 
       if (typeof(obj[i]) == "object" && obj[i].length < 1) 
        findInObjectsOfObjects(obj[i]) 
       else { 
        return obj[i]; -- but loop breaks here 
       } 
      } 
     } 

にある試してみました

for (var obj1 in obj) { 
    findInObjectsOfObjects(obj1).indexOf(3) // instead will be using indexOf 
} 

ただし、最初の配列を返して折り返します。問題は、それが巣のどんな深いことでもよいということです。

+1

'配列またはオブジェクトをobj'か? –

+0

その対象を修正して... !! – Luckyy

答えて

0

内部オブジェクトの値とカスケード戻りをチェックすることで、反復的かつ再帰的なアプローチをとることができます。

function find(object, value) { 
 
    var result; 
 
    Object.keys(object).forEach(function (k) { 
 
     var found; 
 
     if (Array.isArray(object[k]) && object[k].indexOf(value) !== -1) { 
 
      result = result || {}; 
 
      result[k] = object[k]; 
 
      return; 
 
     } 
 
     if (object[k] && typeof object[k] === 'object') { 
 
      found = find(object[k], value); 
 
      if (found) { 
 
       result = result || {}; 
 
       result[k] = found; 
 
      } 
 
     } 
 
    }); 
 
    return result; 
 
} 
 

 
var object = { trees: { small: [1, 2, 3], medium: [4, 5, 13], large: [1, 2, 10] }, plants: { small1: [11, 12, 3], medium1: [14, 15, 3], large1: [11, 12, 10] } }, 
 
    result = find(object, 3); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

関連する問題