0

我想得到"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": ""
    }
4

2 回答 2

0

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

于 2020-04-15T00:15:03.127 回答
0

我从另一篇文章中找到了解决方案:

var response = JSON.parse(responseBody);

const result = Object.keys(response).find(v => response[v].shipping === 'ABC');

//your object keys are equal to id, you can just return key
console.log(result);

// if your object keys can be different from id you can do this
console.log(response[result].shipping_id);
于 2020-04-15T11:11:02.807 回答