Javascript array.find()仅在第一个实例中找到

时间:2016-10-03 09:57:12

标签: javascript

我有以下对象数组:

var data = {};

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

我尝试做的是找到testContent的价值,基于找到它所属的对象,搜索它的父母和兄弟姐妹:

/* 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 */

这适用于第一个对象,但无法找到下一个对象,给出错误:

  

无法阅读属性' testVar'未定义的

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

1 个答案:

答案 0 :(得分:2)



var data = {};

data.type = {
	"types": [{
    	"testA": {
        	"testVar": "abc",
            "testContent": "contentA"
        }
    }, {
    	"testB": {
        	"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);




在测试其属性之前,只需检查您的条目是否存在。