-2

I have an object

const myObject = {rice : 10, wheat: 20, sugar: 3}

I would like to convert it to an array of object:

myArray = [
{"product" : rice, "QTY" : 10},
{"product" : wheat, "QTY" : 20},
{"product" : sugar, "QTY" : 3}
]

Please help. Thanks.

Sky Lurk
  • 417
  • 1
  • 3
  • 13

1 Answers1

2

This is where Object.entries, destructuring and shorthand property names can serve:

const myObject = {rice : 10, wheat: 20, sugar: 3}

const result = Object.entries(myObject).map(([product, qty]) => ({ product, qty }));  
console.log(result);
trincot
  • 317,000
  • 35
  • 244
  • 286