javascript - 在对象数据集上使用 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) {
???
}
});
解决方案
你在第二个朋友名单上有 , 不见了
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>
推荐阅读
- jmeter - JMeter: Is it possible to add HTTP Request sampler during run?
- azure-devops - Azure DevOps 代理无法启动并显示:错误 1 功能不正确 - 服务无法启动
- python - Python Kivy 实时图表
- angular - 为不可见控件验证 Angular Reactive 表单
- java - 无法解析符号“黄瓜”
- javascript - NodeJS函数的不同路径
- sql - 如何从 Table2 中减去 Table1 的值?
- c# - 如何对列表进行排序
> 定制订单? - c - 试图从 linux 内核中理解一段内联 arm 程序集
- java - 从 Arrays.asList 转换为 Array