I’ll leave an example of JSON data below. I filter the names in this data using beginWith (“P”), but I just want the names beginning with “P” to appear and write that name to a DOM element. Below is the code I used but failed. You can take a look at my codepen account to see how my code works better. codepen: https://codepen.io/BerkayAkgurgen/pen/RwoKBrG
At the moment, as you see the output is ‘true,false,false’, since the first object starts with “P”, and the other ones don’t. .map basically replaces each object with the value of the condition you provide.
The way filter works is, it basically keeps only the objects that meet the specified condition, which is what you want in this case.
So just replace .map with .filter like so:
let dene = data.filter(item =>item.name.startsWith(“P”))
This will return an array of all objects that met the condition, so you’ll have to add a minor change, but I’ll let you figure that out on your own
Of course, if it doesn’t seem to work feel free to ask.
This is because it returns an Array. If you want to access a specific element in that array, say the first one, I think you know how to do that
And now you will have only one object. But you don’t really need the entire object, but only the name property. So access that specific property in the object. Again, I think you know how to do that.
This will solve the issue.
Btw. using console.log() is really a great help in these situations, since you will actually be able to see what you are dealing with, instead of this annoying [object Object] output