Sherin Green
Sherin Green

Reputation: 358

How to replace opening and closing curly braces by square brackets and remove labels on a json array in Java script ES6

I have a json array,

var arr=[
{prjId: 230482046, prj: "#1 Cochran", Type: "Invoice", Date: "07-12-2019", Num: "T5917"},
{prjId: 230482182, prj: "#1 Cochran", Type: "Invoice", Date: "07-12-2019", Num: "T5919"},
{prjId: 210640692, prj: "#1 Cochran", Type: "Invoice", Date: "07-15-2019", Num: "T4256"},
{prjId: 210641051, prj: "#1 Cochran", Type: "Invoice", Date: "07-15-2019", Num: "T4298"},
{prjId: 210641170, prj: "#1 Cochran", Type: "Invoice", Date: "07-15-2019", Num: "T4300"}
];

I want to display this json array items in pdf sheet as table contents so I used pdf make third party library but the problem is, according to their code I need above json array as following format

var arr=[
[prjId,prj,Type,Date,Num],
[ 230482046, "#1 Cochran", "Invoice", "07-12-2019","T5917"],
[ 230482182, "#1 Cochran", "Invoice", "07-12-2019","T5919"],
[ 210640692, "#1 Cochran", "Invoice", "07-15-2019","T4256"],
[ 210641051, "#1 Cochran", "Invoice", "07-15-2019","T4298"],
[ 210641170, "#1 Cochran", "Invoice", "07-15-2019","T4300"]
];

How will I achieve this?

Upvotes: 1

Views: 876

Answers (1)

Nikhil
Nikhil

Reputation: 6643

We can use Object.keys() to get property names of an object, and Object.values() to get property values.

Try this:

var arr=[
{prjId: 230482046, prj: "#1 Cochran", Type: "Invoice", Date: "07-12-2019", Num: "T5917"},
{prjId: 230482182, prj: "#1 Cochran", Type: "Invoice", Date: "07-12-2019", Num: "T5919"},
{prjId: 210640692, prj: "#1 Cochran", Type: "Invoice", Date: "07-15-2019", Num: "T4256"},
{prjId: 210641051, prj: "#1 Cochran", Type: "Invoice", Date: "07-15-2019", Num: "T4298"},
{prjId: 210641170, prj: "#1 Cochran", Type: "Invoice", Date: "07-15-2019", Num: "T4300"}
];

var result = [];

result.push(Object.keys(arr[0]));

for (var item of arr) {
  result.push(Object.values(item));
}

console.log(result);

Upvotes: 3

Related Questions