javascript - 根据属性查找 Postman 子对象
问题描述
我想得到"shipping":"ABC"
下面回复中的第一个项目。在这种情况下,预期的响应应该是37
我不太擅长在 Postman 中编写 Javascript 测试。
谢谢你。
{
"37": {
"shipping_id": 37,
"position": 0,
"status": "D",
"shipping": "ABC",
"delivery_time": "24h-72h"
},
"36": {
"shipping_id": 36,
"position": 0,
"status": "D",
"shipping": "DEF",
"delivery_time": ""
},
"28": {
"shipping_id": 28,
"position": 0,
"status": "D",
"shipping": "GHI",
"delivery_time": ""
}
解决方案
这将返回第一个项目 "shipping": "ABC"
:
// convert response data to array of key-value pairs
const entries = Object.entries(response);
// reduce array to the first matching object
const reducer = (acc, [key, val]) => {
return (acc === null && val.shipping === "ABC") ?
(acc = { [key]: val }) : null;
};
// return the found object or null
const found = entries.reduce(reducer, null);
/*
{
'37': {
shipping_id: 37,
position: 0,
status: 'D',
shipping: 'ABC',
delivery_time: '24h-72h'
}
}
*/
工作示例:
const res = {
"37": {
shipping_id: 37,
position: 0,
status: "D",
shipping: "ABC",
delivery_time: "24h-72h"
},
"36": {
shipping_id: 36,
position: 0,
status: "D",
shipping: "DEF",
delivery_time: ""
},
"28": {
shipping_id: 28,
position: 0,
status: "D",
shipping: "GHI",
delivery_time: ""
}
};
const entries = Object.entries(res);
const reducer = (acc, [key, val]) => {
return (acc === null && val.shipping === "ABC") ?
(acc = { [key]: val }) : null;
};
const found = entries.reduce(reducer, null);
console.log(found);
推荐阅读
- asp.net-mvc - 针对 Microsoft.Net.Sdk.Razor 的项目中的核心 3 会破坏 cshtml Mvc 视图?
- python - 有没有办法创建一个用户列表,以便使用 python 将新用户添加到一个简单的游戏中?
- django - dictsort 没有结果
- java - 参考上述代码,预期结果="ECTTRI" 但实际结果="ECTTRI"
- python-3.x - 与没有属性“lower”的“list”对象相关的错误
- python - 如何从文件中打印最后两个匹配的字符串
- android - HTTPS 证书更新后无法从 Android 应用程序访问网站
- python - 有没有办法添加两个具有恒定时间复杂度的列表或数组的元素?
- javascript - 用Javascript中的键值对展平嵌套数组
- r - Rborist 0.1-17 版在 Windows 中不断崩溃 R 会话