Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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?

share|improve this question
2  
map() returns an array. If you try to output (e.g. via console.log()) an array, it is first implicitly joined, as though you'd done array.join(). The commas are a result of that implicit join. – Utkanos Jul 27 at 18:10
up vote 1 down vote accepted

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

share|improve this answer

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;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.