Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


jang walia
jang walia
7,717 Points

map method

[ { "picture" : "beach1.jpg" }, { "picture" : "beach2.jpg" }, { "picture" : "beach3.jpg" }


mapping through this array showing an extra object "undefined" this is what console.log shows: beach1.jpg beach2.jpg beach3.jpg undefined please help anyone.....

Can you post your complete code?

2 Answers

Please post your complete code, one could only guess as of now. Please note that your array looks like JSON. JSON is actually a string, you should parse it before trying to do something. If your example is supposed to be an array of objects, you need to remove the double quotes from the keys.

If I understand what you're trying to do, it should be something like this:

const exampleArray = [ { picture : "beach1.jpg" }, { picture : "beach2.jpg" }, { picture : "beach3.jpg" } ];

exampleArray.map( item => console.log(item.picture) );
jang walia
jang walia
7,717 Points

url2.txt is the address to array i mentioned above now when i see console it shows all the three images along with the undefined object in the end ''' var address = 'url2.txt'; var show = document.getElementById('show_pic'); var btn = document.getElementById('clickdata'); function getjson(file){ return new Promise((resolve,reject)=>{ const xhr = new XMLHttpRequest(); xhr.open('GET',file); xhr.onload = () =>{ if(xhr.status === 200){ let data = JSON.parse(xhr.responseText); resolve(data);

} else{ reject(Error(xhr.statusText)); }





function domapping(json){ json.map(pic=>{ return generateHtml(pic.picture); });


function generateHtml(data){ console.log(data); }

btn.addEventListener('click', () => { getjson(address) .then(domapping) .then(generateHtml) .then(data=>console.log(data)) .catch(err=>console.log(err))



  .then(data => console.log(data))
  .catch(err => console.log(err))

The three console.log you correctly see, come from then(domapping) . The extra undefined line comes from then(generateHTML). Because the domapping function doesn't explicitly return anything, the promise resolves with an undefined value. The next then method takes that promise and passes its value (undefined) to the generateHTML function, which in turn prints it to the console.