首页 > 解决方案 > How to address a specific JSON object

问题描述

I make a call to a REST-API and get a list of persons in JSON format. How do I just refer to one specific Object e.g. "Adam"?

I make the call via Node.js and would like to pass the Javascript object to another function.

I use:

request('rest-api-URL', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(response.body);    // Prints the JSON object
    var object = JSON.parse(body);
    console.log(Object.keys(name)[0]);
  }

Maybe my problem is that I can not express my question clearly (and do not find any information)

This is the JSON:

"persons": [
        {
            "name": "Adam",
            "age": "20",
        },
               {
            "name": "Bob",
            "age": "21",
        },        {
            "name": "Christy",
            "age": "22",
        }    
]
}

标签: node.jsrestapi

解决方案


您可以使用 JavaScript filter() 函数:

array.filter(entry => entry.name == 'Adam')[0]

filter() 函数将返回一个匹配对象的数组,因此末尾的 [0] 因为它将返回一个包含一个对象的数组。


推荐阅读