从json响应创建一个文本

时间:2018-03-13 20:01:31

标签: json node.js

我正在从我的节点js进行api调用并在json中获得响应。以下是我的代码。

apiServices.getCaseStatus("status", function(data) {
                    console.log(JSON.stringify(data));
                    if (data) {
                        console.log(`${data.length} is the length of the data returned`);
                    }

我在进行API调用时获得的JSON如下所示。

[
  {
    "status_details": "requirements",
    "status": "pending"
  },
  {
    "status_details": "requirements",
    "status": "pending"
  },
  {
   "status_details": "forms",
    "status": "pending"
   },
  {
    "status_details": "decision",
    "status": "pending"
   }
]

我想要一个如下所示的声明。

console.log(`${data.length} is the length of the data returned, 2 are pending requirements, 1 is pending decision, and 1 is pending forms`);

我无法知道如何获得此类结果。请帮我这样做。

由于

1 个答案:

答案 0 :(得分:2)

我将它们分组并按status_details计数,然后通过映射其对象键从reduce返回的对象创建字符串

let d = [{
    "status_details": "requirements",
    "status": "pending"
  },
  {
    "status_details": "requirements",
    "status": "pending"
  },
  {
    "status_details": "forms",
    "status": "pending"
  },
  {
    "status_details": "decision",
    "status": "pending"
  }
];

let r = d.reduce((a, b) => {
  a[b.status_details] = a[b.status_details] || {
    count: 0
  };
  a[b.status_details].count += 1;
  a[b.status_details].status = b.status;
  return a;
}, {});

let txt = [d.length + " is the length of the data returned", Object.keys(r).map(e => ' ' + r[e].count + (r[e].count > 1 ? ' are ' : ' is ') + r[e].status + ' ' + e)].join(', ');

console.log(txt);