2

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

1 Answer 1

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

just check if your entry exist before testing his attribute.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmmm - I thought the whole point of .find() was to not have to do this - many thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.