0

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?

1
  • 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. Commented Jul 27, 2016 at 18:10

2 Answers 2

1

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

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

Comments

0

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;

Comments

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.