问题描述
如何在数据集上使用 forEach 函数来获取具有 2 个或更多朋友的对象的名称?我想显示对象有 2 个或更多朋友的名称,所以应该显示“John”。
data.js
const data = [
{
"index": "14","name": "Bob","age": "23","friends": [
{
"id": 0,"name": "Lancaster Howell"
}
],},{
"index": "23","name": "John","age": "30","name": "Lancaster Howell"
}
{
"id": 1,]
app.js(我正在尝试的)
data.forEach((object) => {
if (object.friends.length > 1) {
???
}
});
解决方法
嘿,你可以这样使用。
acc
,
你有一个,失踪在第二个好友列表中
const data = [
{
"index": "14","name": "Bob","age": "23","friends": [
{
"id": 0,"name": "Lancaster Howell"
}
],},{
"index": "23","name": "John","age": "30","name": "Lancaster Howell"
},{
"id": 1,"name": "TONY Howell"
}
],];
data.forEach((objc) => {
if (objc.friends.length > 1) {
objc.friends.forEach((friends) => {
var div= document.getElementById('res');
div.innerText +=friends.name+',';
});}
});
<div id="res"></div>
基于 fynsta 注释的更改,只记录对象名称
data.forEach((object) => {
if (object.friends.length > 1) {
console.log(object.name)
}
});