首页 > 解决方案 > 根据属性查找 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": ""
    }

标签: javascriptpostmanpostman-testcase

解决方案


这将返回第一个项目 "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);


推荐阅读