javascript - 使用js在数组中打印json值

标签 javascript jquery html css reactjs

我正在尝试使用 JS 打印数组中的足球值。我不确定如何在 JS 中打印它。现在,当我尝试时,它打印为 undefined。我在下面提供了我的部分 JS 和 JSON,你们能告诉我如何修复它吗?

if (item.data.football == true) {
    console.log("print football---->" + item.data[0].football);
}
"data": [{
    "sportsProperty": "Insurance",
    "football": true
},
{
    "sportsProperty": "Insurance",
    "football": true
}]

最佳答案

您的对象的data 属性是一个数组,因此您需要通过索引访问其成员。试试这个:

if (item.data[0].football) { // note the [0] after 'data'
    // do something...
    console.log(item.data[0]);
}

以上只会访问数组中的第一项。如果你想使用所有这些你需要使用一个循环,就像这样:

for (var i = 0; i < item.data.length; i++) {
    if (item.data[i].football) {
        // do something...
        console.log(item.data[i]);
    }
}

Working example

关于javascript - 使用js在数组中打印json值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37555867/

相关文章:

html - 向表达式内部 Ruby 字符串中的单词添加文本样式

javascript - 根据显示 flexbox 中的子项设置父项高度/宽度

javascript - WebGL 帧缓冲区多重采样

javascript - 相机 slider ,nivo 灯箱 - jQuery 冲突

javascript - 标签过滤器列表

javascript - 将 slider 添加到博客文章?

javascript - 未捕获的类型错误 : Cannot read property 'value' of undefined in REACT JS

javascript - 将表达式而不是结果传递给指令

php - 使用 JQuery 重定向到 PHP 页面不传输表单内容

jquery - 填充网站表单字段