node.js - 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",
}
]
}
解决方案
您可以使用 JavaScript filter() 函数:
array.filter(entry => entry.name == 'Adam')[0]
filter() 函数将返回一个匹配对象的数组,因此末尾的 [0] 因为它将返回一个包含一个对象的数组。
推荐阅读
- c# - C# 使用 task 和 yield 让 UI 了解正在运行的进程
- laravel - 如何在 laravel 中解决这个错误:ErrorException (E_WARNING) Invalid argument provided for foreach()
- nativescript - 当我使用快捷返回按钮电话时如何在根目录中导航并关闭应用程序
- android - PreferenceFragmentCompat 在 PreferenceCategory 上有我无法摆脱的填充
- javascript - 有通配符导出的语法吗?
- xml - BI Publisher - 忽略部分 - 基于来自 XML 输入数据的信息
- java - 如何覆盖类变量值
- json - 使用 ajv 验证示例 FHIR JSON 捆绑资源
- javascript - 如何添加我的地图
从我的@Controller 到使用 thymeleaf 的 google api 饼图 - java - 如何从 Java 中的字节数组写入 WAV 文件