Home > front end >  Javascript Node.js get all the specific array value
Javascript Node.js get all the specific array value

Time:06-27

This part of code only shows the first and second person in the database "Ban" status.

console.log("Banned0",res.data.data[0].banned); //display the first person banned status
console.log("Banned1",res.data.data[1].banned);  //display the second person banned status

enter image description here

I would like to console.log all 5 person banned status without repeatedly using console.log.

CodePudding user response:

One possible solution, using Array.prototype.forEach:

res.data.data.forEach((data, idx) => console.log('Banned'   idx, data.banned));

CodePudding user response:

If you find an array, you must looping the data, u can use this function

array.map(data => console.log(data));
or
array.forEach((data) => console.log(data));

Read this articles: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration?retiredLocale=id

CodePudding user response:

You can use any kind of for loop to iterate over the data.

My suggestion is to either use a for of loop:

for (const dataItem of res.data.data) {
    console.log("Banned", dataItem.banned);
}

or a forEach loop on the array, which would also easily get you the index:

res.data.data.forEach((dataItem, index) => {
    console.log(`Banned ${index}`, dataItem.banned);
});

CodePudding user response:

The key is to finding a way to iterate over an array of objects each with a banned status. There are a few ways to approach this.

You could use the old-school for statement:

const res={data:{data:[{banned:true,name:"Bob"},{banned:true,name:"Zoe"},{banned:true,name:"Gary"},{banned:false,name:"Fred"}]}};

for (let i = 0; i < res.data.data.length; i  ) {
  const { name, banned } = res.data.data[i];
  console.log(`Is ${name} banned? ${banned}`);
}

You could use forEach. (Note: the limitation of forEach is you can't return a value early if, for example, your loop was in a function, or break or continue).

const res={data:{data:[{banned:true,name:"Bob"},{banned:true,name:"Zoe"},{banned:true,name:"Gary"},{banned:false,name:"Fred"}]}};

res.data.data.forEach(user => {
  const { name, banned } = user;
  console.log(`Is ${name} banned? ${banned}`);
});

Finally here's for...of:

const res={data:{data:[{banned:true,name:"Bob"},{banned:true,name:"Zoe"},{banned:true,name:"Gary"},{banned:false,name:"Fred"}]}};

for (const user of res.data.data) {
  const { name, banned } = user;
  console.log(`Is ${name} banned? ${banned}`);
}

Additional documentation

  • Related