Reputation: 551
I have an array of objects and I want to iterate it and print the field of the objects.
Example console log:
2:{id: "15", nombre: "Intrafungol", categoria: "Antifungicos", efecto: "Lucha
contra la Tiña.", efecto_secundario: "Puede ocasionar hipersalivación,
vómitos, diarrea y/o anorexia.", …}
So this is an example. I want to print the name of all medicines. And my code is not working
function process_data(medicines) {
for(var medicine in medicines ) {
console.log(medicine["name"]);
Thanks a lot!
Upvotes: 1
Views: 373
Reputation: 591
for (i in array)
gives you the indices (enumerable properties), not the items in the array.
Your example would work if you change it to something like:
for (var medicine in medicines ) {
console.log(medicines[medicine].nombre);
}
But if you are able to use array.forEach()
that is great because you get the item in each callback of the function, and don't have to handle the index at all:
medicines.forEach(function (medicine) {
console.log(medicine.nombre);
});
See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Upvotes: 1
Reputation: 616
I think this is the easiest implementation written in ES6:
const processData = medicines => medicines.forEach(med => {
document
.querySelector('.card')
.insertAdjacentHTML('beforeend', `<h4>${med.nombre}</h4>`);
})
Check it out on JSFiddle
Upvotes: 0
Reputation: 3253
It is easier to use for
loop with arrays:
for (var i=0; i<medicines.length; i++) {
console.log(medicines[i].nombre);
}
Upvotes: 0
Reputation: 551
I'm trying to do this:
function process_data(medicines) {
var html = "";
medicines.forEach(medicine => console.log(medicine.nombre));
for(var medicine in medicines ) {
html += "<div class='card mb-2 col-3 card-medicines'>"
+ "<a data-toggle='modal' href='#modall' style='width: 40%'><img class='card-img-top' src='" + medicine['url'] + "'></a>"
+ "<div class='card-block'>"
+ "<h4 class='card-title'>"
+ medicine.nombre
+"</h4>"
And I can't print medicine['url] and medicine.nombre
Upvotes: 0
Reputation: 49
That one won't work because on the medicine object there is no property name
. Maybe you where refering to nombre
you can try replacing the property and see if it works like this:
function process_data(medicines) {
for(var medicine in medicines ) {
console.log(medicine["nombre"]);
you can also use the forEach
array method
function process_data(medicines) {
medicines.forEach(medicine => console.log(medicine.nombre);
}
Upvotes: 0