user1610950
user1610950

Reputation: 1917

javascript getting fields from an array with objects

I filled up an array with some objects like this and printing it out with JSON.stringifty(obj, null, '\t');

gives me output like this:

[
    {
        "title": "here's the title"
    },
    {
        "description": "this is a description"
    }
]

now I am trying to get the data back from this array with objects inside. Using array.map like this:

var title = objArray.map(function(a) {return a.title;});

when I do:

console.log(title); //the output looks like this
,here's the title,,,

If I manually reach into the array like this

console.log(results[0]['title']); //the output is well formatted
here's the title

why is that and how can I get the map function to not add those additional commas to my returned value?

Upvotes: 0

Views: 111

Answers (2)

Paul
Paul

Reputation: 529

It will return a value for everything in the array so you will get these empty values in the resulting array for the objects that do not have a title. You can check for the value of title before returning the value in the map function though. e.g.:

if (a.title) return a.title;

Upvotes: 0

kevin ternet
kevin ternet

Reputation: 4612

Yes because your 2 elements in your array are :

{
    "title": "here's the title"
}

and

{
    "description": "this is a description"
}

but they haven't the same properties : so when you try to display the property title in the second element, JS interpretor just return undefined

Upvotes: 1

Related Questions