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

What is the best way to specifically target and style a component with CSS in a React application?

I'm facing a small issue with the React modals from Bootstrap in my application. In index.html, I include the following: <link rel="stylesheet" href="/assets/css/bootstrap.min.css"> <link rel="stylesheet" href=& ...

Converting a Dataframe or CSV to a JSON object array

Calling all python experts, I have a simple query that needs addressing. Take a look at the data below: 0 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed959691ab9f92d1dcc0c2">[email protected]</a> 1323916902 ...

selecting a radio button and saving its value into a JavaScript variable

How can I assign the return value from a JavaScript script function to a variable inside the HTML body? The function will return the selected variable, but how can I assign it to a variable within my HTML body? <body> <form action="somepage.php ...

How come jQuery is retaining the original DOM element classes even after I have modified them using jQuery?

Here is the code snippet I am working on: $(".drop-down-arrow-open i").click(function(){ console.log("The click function for .drop-down-arrow-open is triggered even when it is closed"); let thisParent = $(this).closest(".projects-container").find(".need ...

The process of converting a response into an Excel file

After sending a request to the server and receiving a response, I am struggling with converting this response into an Excel file. Response header: Connection →keep-alive cache-control →no-cache, no-store, max-age=0, must-revalidate content-dispositio ...

Submitting the form does not result in the textbox being cleared

I have been attempting to clear the txtSubTotal text box upon clicking the PROCEED button, but it seems that my efforts have been in vain despite trying various code examples, including those from SO. btnProceed/HTML <input type="submit" name="btnProc ...

"Sequelize will pause and wait for the loop to finish before executing the

As someone with a background in PHP, I'm finding the concept of callbacks a bit challenging to grasp. Essentially, I need to retrieve some rows and then iterate through them to compare against another model (in a different database). However, I want ...

Is there a way to set up an HTTP service in Orbeon by utilizing HTTP parameters and extracting data from a JSON response?

Currently, I am exploring the potential of Orbeon for creating forms within my application. This particular application makes use of HTTP web services by passing and receiving JSON data through HTTP parameters. I would like to know how I can set up Orbeon ...

Pause animation when hovering over their current positions

I am working on a project with two separate divs, each containing a circle and a smiley face. The innercircle1 div is currently rotating with a predefined animation. My goal is to create an effect where hovering over the innercircle1 div will pause its rot ...

My CSS seems to be causing an issue and preventing the function from running correctly. Now I just need to

I'm currently working on a project and following a tutorial to help me create a navigation bar. The tutorial I am using can be found here: https://www.youtube.com/watch?v=gXkqy0b4M5g. So far, I have only reached the 22:05 mark in the video. I have su ...

Are ES6 arrow functions not supported in IE?

When testing this code in my AngularJs application, it runs smoothly on Firefox. However, when using IE11, a syntax error is thrown due to the arrows: myApp.run((EventTitle, moment) => { EventTitle.weekView = event => \`\${moment(event.s ...

Chrome extension for AJAX with CORS plugin

Currently, I am utilizing jQuery for cross-origin AJAX requests and attempting to include headers in the request as shown below. However, I am encountering an error message stating that it is an invalid request: $.ajax({ url: address, headers:{ ...

Obtaining a JSONObject for a RealmObject requires a specific process

Currently, I am using Retrofit2 to fetch data and storing it in Realm. However, I am struggling to extract a JSONObject from another JSONObject and save it into a RealmObject. Can anyone guide me on how to define my RealmObject model for this scenario? I a ...

Issue with Axios code execution following `.then` statement

Recently diving into the world of react/nodejs/express/javascript, I encountered an interesting challenge: My goal is to retrieve a number, increment it by 1, use this new number (newFreshId) to create a new javascript object, and finally add this event t ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

How can we minimize the data contained in JSON HTML markup?

https://i.stack.imgur.com/mzuB0.png Currently, I am attempting to find a way to conceal the last 12 digits in the price shown on a button, as it is excessively long. The method I am utilizing involves a JSON api and insertAdjacentHTML markup. This snipp ...

Adding my 'no' or 'id' in a URL using a JavaScript function can be accomplished by creating an onClick event

Here is the function I'm working on: function swipe2() { window.open('edit.php?no=','newwindow') } This is part of my PHP code (I skipped some lines): for ($i = $start; $i < $end; $i++) { if ($i == $total_results) { ...

Sending a string of HTML elements to a Vue custom directive is causing problems with the eslint code analysis

I have developed two custom Vue directives to add an HTML element before or after another element. I provide an HTML string to the element where I apply the directive, but I am encountering an error in VS Code: Parsing error: unexpected-character-in-a ...

Ensuring uniqueness in an array using Typescript: allowing only one instance of a value

Is there a simple method to restrict an array to only contain one true value? For instance, if I have the following types: array: { value: boolean; label: string; }[]; I want to make sure that within this array, only one value can be set to t ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...