[英]Javascript Node.js get all the specific array value
This part of code only shows the first and second person in the database "Ban" status.这部分代码只显示了数据库“Ban”状态的第一人和第二人。
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
I would like to console.log all 5 person banned status without repeatedly using console.log.我想在不重复使用 console.log 的情况下 console.log 所有 5 人被禁止的状态。
一种可能的解决方案,使用Array.prototype.forEach
:
res.data.data.forEach((data, idx) => console.log('Banned' + idx, data.banned));
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阅读这篇文章: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration?retiredLocale=id
You can use any kind of for
loop to iterate over the data.您可以使用任何类型的
for
循环来迭代数据。
My suggestion is to either use a for of loop:我的建议是要么使用 for of 循环:
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:或数组上的 forEach 循环,这也可以轻松获得索引:
res.data.data.forEach((dataItem, index) => {
console.log(`Banned ${index}`, dataItem.banned);
});
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
:您可以使用老式的
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
.你可以使用
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
). (注意:
forEach
的限制是你不能提前返回一个值,例如,如果你的循环在一个函数中,或者break
或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
:最后是
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附加文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.