Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data:

var originalData = {
    "1": "alpha",
    "2": "beta",
    "3": "ceta"
}

The desired format is as follows:

var convertedData = [
    {id: 1, label: "alpha"},
    {id: 2, label: "beta"},
    {id: 3, label: "ceta"}
];

If anyone has suggestions on how to achieve this conversion, please share them. Thank you!

Answer №1

Here is a suggestion for you to try:

var a = {
  "1": "alpha",
  "2": "beta",
  "3": "ceta"
}

var b = [];

for (var key in a) {
  if (a.hasOwnProperty(key)) {
    b.push({
      "id": key,
      "label": a[key]
    });
  }
}

console.dir(b);

Please take note - Make sure to update your object a by adding commas where necessary.

Answer №2

This specific suggestion utilizes Object.keys() along with the function Array#map().

var a = { "1": "alpha", "2": "beta", "3": "ceta" },
    b = Object.keys(a).map(function (k) {
        return { id: k, label: a[k] };
    });

document.write('<pre>' + JSON.stringify(b, 0, 4) + '</pre>');

Answer №3

experiment

let arrayB = [];

for ( let property in objectA )
{
   arrayB.push( { identifier : property, value : objectA[property] } );
}
console.log(arrayB);

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

Tips for preventing multiple button clicks until the completion of the initial click event

I created a clock that tells the time every quarter as per the professor's request. However, there is an issue - when I click multiple times, the clock keeps telling the time repeatedly until the number of tellings matches the number of clicks. I thou ...

Receiving an empty string from Chrome FileReader when dealing with large files (300MB or more)

Objective: The task is to read a file from the user's file system as a base64 string in the browser The size of these files can be up to 1.5GB Challenge: A script that works flawlessly on Firefox, regardless of the file size On Chrome, the script p ...

How can I properly redirect an HTTP request to HTTPS on my Express server?

Currently, I am working on my API and have configured it to work with the HTTPS protocol using SSL. Here is the code snippet: https.createServer({ key: fs.readFileSync(certKeySSLPath), cert: fs.readFileSync(certSSLPath) }, app).listen(serverPORTHTT ...

"Encountering a connectivity problem with Apollo server's GraphQL

I am facing a networking issue or possibly a bug in GraphQL(Apollo-Server-Express). I have tried various solutions but to no avail. When sending a query, everything seems perfect - values checked and request showing correct content with a 200 status code. ...

What is causing the issue with $(document).append() method in jQuery version 1.9.1?

Why is the following code not functioning properly in jQuery 1.9.1? It worked fine in previous versions. $(function () { $(document).append(test); document.write('done'); }); var test = { version: "1.0", }; JSFiddle: http://jsfiddl ...

Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows: <h1>{{myproperty1}}<\h1> <h1>{{myproperty2}}<\h1> <h1>{{myp ...

Is there a way for ResponsiveSlides to fade the pager without causing any disruption to the content below, all

I have been working with the Responsive Slides jQuery plugin and made some custom modifications. Everything is going smoothly, but I am facing an issue with getting the pager and next/prev controls to fade in when hovering over the container. Although I s ...

Tips for utilizing Vue 'component' with just Vue added as a page add-on using <script>:

I am trying to incorporate a Vue component called vue-timeago: import VueTimeago from 'vue-timeago' Vue.use(VueTimeago, { name: 'Timeago', // Component name, `Timeago` by default locale: undefined, // Default locale locales: { ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

manipulating dropdown visibility with javascript

I'm feeling a bit lost on how to structure this code. Here's what I need: I have 5 dropdown boxes, with the first one being constant and the rest hidden initially. Depending on the option chosen in the first dropdown, I want to display the corres ...

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

Is there a way to optimize app speed in Angular2 by importing CommonModule and RouterModule in a centralized location?

I find myself constantly importing these two modules in almost every component: import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; Is there a way to import them only once in the global app. ...

Using JQuery to Customize Navigation Menu Targeting

On my website, I am trying to make an href button and a menu fade in as the page loads. However, I am struggling to find the correct code due to its placement within multiple tags, especially since I am new to JS and JQuery. I have provided a fiddle with a ...

I am interested in extracting information from a public Facebook post

Is it possible to scrape or utilize the FB API to retrieve data from a public profile's wall post? By inspecting the element on the URL, you can see most of the data as well as the ajax calls for infinite scrolling on the wall. How could one go about ...

When using jQuery's ajax() function, it is possible to pass HTML as data and change the ampersands in URLs to &amp;

I have encountered an issue where I am capturing the HTML content of a page and attempting to send it as a string to a PHP web service using jQuery's ajax() function. However, when I receive the parameter on the PHP side, the &s in the URLs present wi ...

Utilize Material UI AutoComplete in React to showcase a variety of choices in a list and capture various selections in the form state, including multiple values

I'm looking to implement Autocomplete in a way that it saves a specific property of an object in the form state and displays a different property in the autocomplete options list. For instance, if we have the following option list: [ { gender_name ...

Setting up of imagemagick node module using linuxbrew

Having trouble installing imagemagick-native as it's showing an error. Tried using the following command to install: npm install imagemaick-native --save > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c45414d ...

Guide to: Decoding JSON Data

I've been struggling to deserialize this in C# but so far haven't had any luck. Any help would be greatly appreciated. Here is the JSON data: { "138c399": [ "A1E67B", 39.826, -76.9241, 238, 15400, 402, "2573", "T ...

Is there a way to activate the jquery event handler only when certain events occur in a particular sequence?

Currently, I am facing a particular scenario involving the use of Bootstrap tabs in combination with MarionetteJS. I want to ensure that when a tab is clicked, my designated handler function is only called after the 'show.bs.tab' event for that s ...

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...