2016-10-03 4 views
2

は、私は次のオブジェクトの配列を持つ最初のインスタンス内で見つかりましたそれは、親や兄弟です:Javascriptのarray.findは()のみ

/* within the data, find content where parent is testA and sibling testVar is "abc" */ 
var findSet = data.type.types.find(function(entry) { 
    return entry['testA'].testVar === "abc"; 
}); 

console.log(findSet['testA'].testContent); /* returns string "contentA" as expected */ 

これが第一の目的のために正常に動作しますが、エラーを与えて、次のオブジェクトを見つけることができない:

Cannot read property 'testVar' of undefined

var findSet = data.type.types.find(function(entry) { 
    return entry['testB'].testVar === "def"; /* Cannot read property 'testVar' of undefined */ 
}); 

console.log(findSet['testB'].testContent); 

他にどのようなものが必要なのでしょうか?

Here's a fiddle to test the output

答えて

2

var data = {}; 
 

 
data.type = { 
 
\t "types": [{ 
 
    \t "testA": { 
 
     \t "testVar": "abc", 
 
      "testContent": "contentA" 
 
     } 
 
    }, { 
 
    \t "testB": { 
 
     \t "testVar": "def", 
 
      "testContent": "contentB" 
 
     } 
 
    }] 
 
}; 
 

 
var findSet = data.type.types.find(function(entry) { 
 
    return entry['testA'] && entry['testA'].testVar === "abc"; 
 
}); 
 

 
console.log(findSet['testA'].testContent); 
 

 
var findSet = data.type.types.find(function(entry) { 
 
    return entry['testB'] && entry['testB'].testVar === "def"; /* Cannot read property 'testVar' of undefined */ 
 
}); 
 

 
console.log(findSet['testB'].testContent);

あなたのエントリは彼の属性をテストする前に存在している場合だけ確認してください。

+0

Hmmm - '.find()'の全体的なポイントがこれを行う必要がないと思った - とにかく多くの感謝 –

関連する問題