首页 > 解决方案 > 在对象数据集上使用 forEach

问题描述

如何在数据集上使用 forEach 函数来获取具有 2 个或更多朋友的对象的名称?我想显示对象有 2 个或更多朋友的名称,因此应显示“John”。

数据.js

const data = [
 {
    "index": "14",
    "name": "Bob",
    "age": "23",
    "friends": [
        {
          "id": 0,
          "name": "Lancaster Howell"
        }
     ],
  },
  {
    "index": "23",
    "name": "John",
    "age": "30",
     "friends": [
        {
          "id": 0,
          "name": "Lancaster Howell"
        }
        {
          "id": 1,
          "name": "Lancaster Howell"
        }
     ],
  },

]

app.js(我正在尝试)

data.forEach((object) => {
  if (object.friends.length > 1) {
    ???
  }
});

标签: javascriptarraysjsonforeach

解决方案


你在第二个朋友名单上有 , 不见了

const data = [
 {
    "index": "14",
    "name": "Bob",
    "age": "23",
    "friends": [
        {
          "id": 0,
          "name": "Lancaster Howell"
        }
     ],
  },
  {
    "index": "23",
    "name": "John",
    "age": "30",
     "friends": [
        {
          "id": 0,
          "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>


推荐阅读