create a text from a json response

204
March 14, 2018, at 11:02 AM

I'm making an api call from my node js and getting a response in json. And below is my code.

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

And the JSON that I get when I make the API call is as below.

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

Here I want a statement like below.

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

I am unable to know how I can get this type of result. please help me in doing this.

Thanks

Answer 1

I'd group them and count by status_details, then create your string from the object the reduce will return by mapping over its object keys

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);

Rent Charter Buses Company
READ ALSO
Run a mocha test with multiple js files and generate separate JSON reports

Run a mocha test with multiple js files and generate separate JSON reports

I have several mocha & chakram test case files, located on current directory:

145
how to protect server side script and hidden which are writing with Node.js

how to protect server side script and hidden which are writing with Node.js

Above code have some private information like database name, user, password and SQL query tooI am new in node

175
Why is this data being stored as a string and not a float? (Python)

Why is this data being stored as a string and not a float? (Python)

I am writing a simple Python program to store user inputted lap times in a list and then have a few functions performed on that list

258
Python print function not rendering graph

Python print function not rendering graph

When I run the below code, no graph is printed

231