1

My data:

{product_quantity: {quantity: 13, code: "AAA", warehouse: "1000",}}

product_quantity is an field from a mongodb json data.

I need to convert it into this:

{"product_quantity": [{"quantity": 13, "code": "AAA", "warehouse": "1000"}]

How can I transform an object into array with its keys and values?

Thanks.

ALBINO33
  • 31
  • 7
  • 1
    Does this answer your question? [How to convert JSON object to JavaScript array?](https://stackoverflow.com/questions/14528385/how-to-convert-json-object-to-javascript-array) – ahmet gül Aug 08 '22 at 13:40
  • 1
    `[quantity]`? Hard to tell where the difficulty is... – Ruan Mendes Aug 08 '22 at 13:45
  • No, I need the same variable to be converted. Not creating an array and inserting data into it – ALBINO33 Aug 08 '22 at 13:50
  • 1
    `quantity = [quantity];` It's till hard to tell what you are trying to do and what you're having difficulty with. – Ruan Mendes Aug 08 '22 at 13:51
  • So my data comes from a mongodb. I put it as const to exemplify, to simplify the question. I need to convert the data using some method. Because I will need to continue my code using the data transformed into an array – ALBINO33 Aug 08 '22 at 13:56
  • 1
    Read [ask] and create a proper [mcve] of the problem – Alon Eitan Aug 08 '22 at 13:57
  • `const` means you can't change what it references... I don't see how your requirement is real. Assign it to something else and pass your new reference back where you need it. – Ruan Mendes Aug 08 '22 at 13:58
  • @ALBINO33 json you want is not valid – Serge Aug 08 '22 at 14:20

2 Answers2

1

const data = [quantity];

output; [{quantity: 13, code: "AAA", warehouse: "1000",}];

korayaggul
  • 72
  • 5
  • I've edited the question, I think it is now clearer to understand. Thanks for the help – ALBINO33 Aug 08 '22 at 14:05
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 11 '22 at 06:48
1

json you want is not valid , you can use this

let productQuantity={product_quantity:{quantity:13, code:"AAA", warehouse:"1000"}};

productQuantity.product_quantity=[productQuantity.product_quantity];

console.log(JSON.stringify(productQuantity));

result

{"product_quantity":[{"quantity":13,"code":"AAA","warehouse":"1000"}]}
Serge
  • 40,935
  • 4
  • 18
  • 45