Joey Marinello
Joey Marinello

Reputation: 582

JavaScript - Unable to correctly access properties within object

I have the following code:

function getObjects(name, data) {
    return data.filter(function(d) {
        return name.title == d.title;
    }).map(function(d) {
        return {
            "title": d.title,
            "sort": d.sort[0],
            "direction": d.sort[1],
            "columns": d.columns
        }
    });
};
var objectMatch = getObjects(searchName, searchObjects);
console.log("------match------");
console.log(objectMatch);

When I print objectMatch to the console, I get the following output:

[ { title: 'Convene LinkedIn Import - True',
sort: '_type',
direction: 'asc',
columns: [ 'm-Form Factor_s', '_type', 'm-Identity_s' ] } ]

I am trying to access the properties inside this object, but I keep getting undefined when trying to reference them as the following:

var title = objectMatch.title;

What is the correct way to reference the properties inside of the objectMatch variable?

Upvotes: 0

Views: 45

Answers (1)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107536

map() returns an array, so you'd have to do:

var title = objectMatch[0].title;

If your getObjects function will/should never return more than one item, I would instead change your function to:

function getObjects(name, data) {
    return data.filter(function(d) {
        return name.title == d.title;
    }).map(function(d) {
        return {
            "title": d.title,
            "sort": d.sort[0],
            "direction": d.sort[1],
            "columns": d.columns
        }
    })[0];
};

Then you can access the title as you were before.

Upvotes: 1

Related Questions