What is the best way to transform a JavaScript object into an array?

Here is the information I have:

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

The product_quantity field is part of a JSON object in a MongoDB database.

I am looking to convert it into this format:

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

Is there a way to transform an object into an array with its keys and values?

Thank you for your help.

Answer №1

The JSON you are trying to access is invalid, but I have a solution for you:

let itemQuantity={item_quantity:{quantity:10, code:"BBB", warehouse:"2000"}};

itemQuantity.item_quantity=[itemQuantity.item_quantity];

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

Here is the final result:

{"item_quantity":[{"quantity":10,"code":"BBB","warehouse":"2000"}]}

Answer №2

let newData = [quantity];

result; [{quantity: 13, code: "AAA", storage: "1000",}];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I configure Material-UI's textfield to return a numerical value instead of a string when the type is set to "number"?

Utilizing Material-UI's TextField alongside react-hook-form to monitor inputs has raised an issue for me. I have observed that regardless of the input type, it always returns a string. This creates conflicts with the data types I am using in my codeba ...

Encountering a problem: array property length not found in Angular application?

I am trying to create a list of superheroes by looping through an array, but I keep encountering an error stating that the property length is missing from the array. (please refer to the screenshot) Here is my code in app.component.ts import { Component ...

The Jquery navigation and image display features are experiencing technical difficulties in Internet Explorer

My website is currently in the development stage and functions well on all browsers except for IE10. Interestingly, both the menu bar and photo gallery, which rely on Jquery, are not functioning properly in IE10. Below is the code snippet: <script ty ...

Can an Angular Component be displayed using a Serverless function like Lambda on AWS?

I have a single-page application developed in JavaScript using the Angular 6 Framework, and I am interested in dynamically rendering an Angular Component that is hosted on a remote server. Currently, I am utilizing viewContainerRef to dynamically render ...

Invalid extra parameters in the $.ajax function

I am attempting to access a web service in order to retrieve some data. I must include this URL using the GET method: http://localhost/ecosat/ws/api.php?t=vw_motorista However, when I check in Chrome Developer Tools, the link is shown as: http://localho ...

Exploring the world of Ajax with jQuery

Could someone help me figure out how to integrate Ajax into my PHP code so that the content can load dynamically? Currently, it looks something like this: First, a user selects a category: <li><a href='?genre=sport'>Sport</a>& ...

Create a JSON structure with nested elements

I've been attempting to create a nested JSON from a simple JSON but haven't been successful yet. Here is the JSON structure I'm trying to convert: [ { "station_id": "ESP0001", "datetime": "2022-1 ...

Manipulating the DOM to show various elements upon clicking on text

Currently, I am engaged in a small project that involves experimenting with DOM manipulation. The project revolves around creating a Todo list where users can generate various categories (such as work, gym, finances, etc.) and then add corresponding subtas ...

Oops! An issue has occurred where I am unable to access certain properties (specifically 'Symbol(__APOLLO_CONTEXT__)') while utilizing the Apollo provider

When attempting to implement a query in my upcoming app, I encountered an error that reads: Error: Cannot read properties of undefined (reading 'Symbol(APOLLO_CONTEXT)') This is the setup of my Apollo client: import { ApolloClient, InMemoryCache ...

Using an id as the attribute value for a React ref

I have a question about referencing DOM nodes in a component. Currently, I am able to get the nodes and children using the following code: export class AutoScrollTarget extends React.Component { constructor(props) { super(props); this ...

My code to hide the popup when clicking outside doesn't seem to be working. Can you help me figure out why?

After searching around on stackoverflow, I stumbled upon a solution that worked for me: jQuery(document).mouseup(function (e){ var container = jQuery(".quick-info"); if (container.has(e.target).length === 0) { container.hide(); } }); ...

Whenever I hit the refresh button, `$locationprovider.html5mode` seems to deactivate my CSS styling

Things go smoothly as long as I remove $locationprovider.html5mode(true). However, enabling html5mode seems to be causing some troubles. The main issue is that the css styles stop working after page refreshes. Any ideas on what could be causing this and ...

How to display 3 items per row in a React table by utilizing a map function loop

Currently, my table using material UI generates one column on each row. However, I would like to display 3 columns as items on each row. Below is the mapping for my table: <TableBody> {this.props.data.slice(page * rowsPerPage, page * rowsPerPage ...

Angular - send multiple HTTP requests for the length of an array and combine the responses into one array

Exploring angular for the first time and dabbling with the trello API. I have an array containing some list IDs that I need to make HTTP GET calls for, equal to the length of the array. For instance, if there are two IDs in the array, then the HTTP call sh ...

"The TextInput component in ReactNative is preventing me from inputting any text

Experiencing issues with the iOS and Android simulators. Upon typing, the text disappears or flickers. I attempted initializing the state of the texts with preset values instead of leaving them empty. However, this caused the TextInput to stick to the ini ...

What is the process for retrieving data submitted in JSON format?

Hello there! Programming Query: $("#user-search_input").autocomplete({ source: function( request, response ) { var form_data=$("#user-search_input").val(); $.ajax({ url: "./AutoCompliteFind/", dataType: "json", typ ...

Is the $ajax() function truly asynchronous when invoking a success callback?

I find myself in a state of confusion at the moment. The asynchronous ajax call I have set up includes a success callback function being passed in. ajax('PUT', 'some URL', successCallback, data); I notice that this callback is trigger ...

When a property is passed as a prop in a Vue component, it is received

https://jsfiddle.net/2xwo87bs/ In order for Vue to properly handle the object prop that is being passed to the component, it is necessary to first convert the string into an actual object. While in the provided snippet I have used JSON.parse() as a qui ...

Loading an OBJ file from a blob using three.js

I am currently attempting to load an OBJ file from a blob using Three.js. After referring to this resource and successfully loading STL files, I encountered an issue with loading OBJ files. The error message I received is as follows: TypeError: text.indexO ...

Encountering an issue while constructing an Angular library project. The 'ng serve' command runs smoothly on local environment, but an error message stating

I recently developed an npm package called Cloudee. While it functions perfectly locally, I encounter an issue when attempting to deploy it. The error message states: 'Unexpected value 'CloudyModule in /home/hadi/dev/rickithadi/node_modules/cloud ...