如何从JSON数组中获取JSON对象值

时间:2017-08-19 08:22:50

标签: javascript json

我解析来自第三方API调用的数据

"flows":[                          
    {
      "psy_num" : 3,
      "Age" : 25,
      "Results" : "You are smart enough to get into business" 
    }   
    ,
    {
      "psy_num" : 1,
      "Age" : 25,
      "Results" : "You are smart enough to get into business"
    }
    ,
    {
      "psy_num" : 3,
      "Age" : 28,
      "Results" : "You are smart enough to get into business"
    }    
]

如何根据两个关键数据获取json对象值? 例如,我的psy_num为3,年龄为25,那么它将显示结果数据。结果数据应取决于两个psy_num和年龄。如果用户有psy_num且年龄匹配,则会向用户显示结果数据。

以前我用过

我计算从用户出生日期到年龄的年龄。我也得到psy_num,它是从出生日起的一天(2 + 1 = 3)的总和。

let flowData = JSON.parse(body);

function getResults(key, flowData) {
    var i, len = flowData.length;

    for (i = 0; i < len; i++) {
        if (FlowData[i] && flowData[i].hasOwnProperty(key)) {
            return flowData[i][key];
        }
    }
    return -1;
}
console.log(getResults('psy_num', flowData.flows));`

这是实际的JSON文件

https://script.googleusercontent.com/macros/echo?user_content_key=lqIrhrynJpI_9UZ7nxCi02IC6PJmilqVpAZu5qIH-NHKjJQsnpuxQvcXAwEYtPVGo7WUG4zt8U4X7Rrd4r7eGFNJdS71X83pOJmA1Yb3SEsKFZqtv3DaNYcMrmhZHmUMWojr9NvTBuBLhyHCd5hHa1ZsYSbt7G4nMhEEDL32U4DxjO7V7yvmJPXJTBuCiTGh3rUPjpYM_V0PJJG7TIaKp0gzTkmNhWNdTTY0t4K_dLqFVQC0BmEoHh1iraj-hUoovHjOg3Oej01Fd1uEZR7p_DU9HkkyTh_9SkCMY51DGu3m4vHBGULOCg&lib=MbpKbbfePtAVndrs259dhPT7ROjQYJ8yx

1 个答案:

答案 0 :(得分:2)

要在数组中搜索,您可以使用filter()函数:

flowData.filter(arrayItem => {
    // here is condition
    return arrayItem.psy_num = your_psy_value && arrayItem. Age = your_age_value;
})