Creating multiple objects using a single object in JavaScript can be achieved by using the concept of object

When presented with the following data structure:

 {
     "time_1": 20, 
     "time_2": 10,
     "time_3": 40, 
     "time_4": 30
 }

and expecting a result in this format:

[
 {
  "key1": "time_1",
  "key2": 20,
 },
 { 
  "key1": "time_2",
  "key2": 10,
 },
 { 
  "key1": "time_3",
  "key2": 40,
 },
 { 
  "key1": "time_4",
  "key2": 30,
 }
]

Is there a way to convert an object into an array using JavaScript? I have revised my initial question.

Answer №1

If you want to convert your object into an array, you can utilize the Object.keys() method to iterate over the object and then use the Array.map() method to achieve the desired structure.

var originalData = {
  "0": "value1",
  "1": "value2"
}

var transformedData = Object.keys(originalData).map(key => ({
  [key]: originalData[key]
}))

console.log(transformedData)

--Edited Version--

To modify the output of the .map() method, simply adjust the object being returned within the callback function.

var data =  {
     "time_1": 20, 
     "time_2": 10,
     "time_3": 40, 
     "time_4": 30
 }

var newData = Object.keys(data).map(key => ({
  "name": key,
  "duration": data[key]
}))

console.log(newData)

Answer №2

provided information

const info = {
 "time_1": 20, 
 "time_2": 10,
 "time_3": 40, 
 "time_4": 30

}

retrieve all keys from the info object

const KeysOfInfo = Object.keys(info);

desired outcome should be as follows - [ { "key1": "time_1", "key2": 20, }, ]

const result = KeysOfInfo.map(key => {
  const value = info[key]
  return {
    key1: key,
    key2: value
  }
});

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

JS: Decreasing the counter while calling the hide() function

If I have a standard count <?php echo "Today (".mysql_num_rows($query)."); ?> It will display as Today (10) if there are 10 entries. Beneath this counter is a while() loop that displays all the rows in a <tr>. Within each <td> in the ...

Using a dynamic HTML interface, select from a vast array of over 50,000 values by leveraging the power

I am working on a project that includes a multiselect option with over 50,000 records. We are using AJAX to fetch data from the server based on user searches, which works fine. However, when a user tries to select all records by clicking the "check all" ...

Creating a Clojure package for improved functionality

Attempting to use the hierarchical-classifier.clj script from GitHub, I encountered an issue when trying to modify the path within *directory-string* to point to my Dropbox directory containing text files. The REPL threw a compiler exception for org.apache ...

The && symbol in JSONPath: combining conditions efficiently

Here is an example of JSON data taken from the tutorial: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", " ...

Ensure the video frame stretches to fit the full width

I am struggling to make my video frame fill the entire width of the screen. Even though I have tried using CSS, the video container does not stretch to the full width as expected. How can I ensure that the video plays across the whole screen width? Here ...

Copy one character array to another character array

Why is it that we cannot simply assign a char array to another char array like this: char array1[] = "Hello"; char array2[] = "Hi!"; array1 = array2; // This will not compile However, the following code does work: char array1[] = "Hello"; char *ar ...

Access the entire appsettings.json configuration data in string format

I am seeking a way to extract the complete contents of my appsettings.json file and parse it using NewtonSoft.JSON for full JSON path capabilities. The goal is to read the entire appsettings.json file as a string without specifying individual settings lik ...

In React js, I wanted to display the animation specifically on the "add to bag" button for the added item

When I click the "add to bag" button, all other buttons also display the animation. How can I make sure that only the clicked button shows the animation? Any suggestions? <Table responsive> <thead> <tr> ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

Troubleshooting: Images not displaying on webpage due to Ajax, JQuery, and JavaScript integration

I'm currently working on building a dynamic photo gallery using Ajax and JQuery in Javascript. I have set up a directory named "images" in Visual Studio Code and it contains my selection of 5 images. However, when I click the "next" and "previous" but ...

How can Python be used to export hierarchical JSON data into an Excel xls file?

Looking to transfer data from Python to xlsx format. Currently have the data stored in JSON format. It doesn't matter what type of data is being exported out of Python. Here's an example JSON structure for a single article: { 'Word Coun ...

What are the most effective strategies for managing vast amounts of data using JS fetch?

The server is taking about 2 minutes to export a large JSON data, resulting in a timeout error on the client side before receiving a response from the server. I have searched online for solutions, but I cannot find a way to extend the timeout or continue ...

Struggling to parse JSON using jax-rs from a REST API into POJOs due to modifications in the JSON structure?

My REST Client Class was working perfectly using javax.ws.rs.WebTarget, .Client and javax.ws.rs.core.MediaType to interact with a server's REST service that returned a JSON String. However, I recently encountered an issue where the format of the JSON ...

Using the .show() function will not alter the outcome or trajectory

I am currently working with some divs in my project where I want to implement the JQuery functions .show() and .hide(). However, I have encountered an issue where I am unable to change the effects or directions of these animations. Here is a snippet of th ...

What is the best way to deliver an HTML document in Express from a directory that is one level higher than my server folder?

I am facing an issue while trying to access an HTML file from my main directory through my Express server, which is located one level deeper in the server folder. Below is the configuration of my server code: const express = require('express') ...

Mysterious symbols appearing in text/html encoding on Firefox

When I retrieve a text/html content from a ".txt" file using jquery.ajax(), everything works fine in other browsers except for Firefox. In Firefox, I see strange characters like ... This is my code: $.ajax({ url: "menuProcesso.txt", ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Is there a way to select only a single line from an HTML document?

Is there a way to extract just one specific line from an HTML file? Let's say we have the following file: <!DOCTYPE html> <html> <head></head> <body> This is a test string. This is another test st ...

Tips on eliminating the 'first', 'previous', 'next', and 'last' buttons in the twbs pagination plugin

I am searching for a straightforward pagination solution that only displays page numbers without control buttons like "first," "previous," "next," and "last." I have looked through the options available in twbs-pagination's github documentation and on ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...