当前位置: 动力学知识库 > 问答 > 编程问答 >

Javascript array.find() only finds within first instance

问题描述:

I have the following object array:

var data = {};

data.type = {

"types": [{

"testA": {

"testVar": "abc",

"testContent": "contentA"

}

}, {

"testB": {

"testVar": "def",

"testContent": "contentB"

}

}]

};

What I'm trying to do is find the value of testContent based on finding the object it belongs by searching it's parent and sibling:

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

This works fine for first object but fails to find next object, giving error:

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);

How else could I find what's needed?

Here's a fiddle to test the output

网友答案:

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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: