An elegant approach to converting a JavaScript object containing key-value pairs into an array of objects, each with a single key-value pair

Essentially, I have an enum that represents different statuses

status = {1: "new", 2: "working" ... }

and my goal is to transform it into something like

status = [{1: "new"}, {2: "working"} ...]

in a way that is clean and easy to understand.

At the moment, I'm unsure of the best approach. Perhaps iterating through the object and creating a new object in an array for each pair? However, this does not sound like the most efficient method.

Answer №1

By using Object.entries(data) and mapping through the array, you can create a new array with key-value pairs as objects.
This results in an array of the format you desire. Alternatively:

You can achieve the same result by initializing an empty array called arrayData and looping through each key in data to push key-value pairs as objects into the array.

Answer №2

Exploring the flexibility of iterating through dynamic objects:

const object1 = {
  a: 'anotherstring',
  b: 87
};

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key} - ${value}`);
}

Answer №3

const { shape } = require("prop-types")

const condition = { A: "good", B: "fair" }

const updatedCondition = Object.entries(condition).map(([key, val]) => ({ [key]: val }))

console.log(updatedCondition);

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

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Error encountered in Three JS Drag Controls: Unable to assign value to property 'x' as it is undefined

I've been trying to drag the spheres around the scene using drag controls that should be activated when the "m" key is pressed. However, I keep running into an issue where the objects don't move and I receive an error message saying "Uncaught Typ ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

The process of eliminating body padding in Nuxt.js

I'm considering building a website using Nuxt.js because I've heard it's both cool and user-friendly. While I do have some knowledge of vue.js, I'm stuck on a particular issue: How can I remove the padding from the body? I understand ...

Use JQuery's $ajax to exclusively retrieve items that have a date prior to the current date

In my jQuery code, I have a function called fetchResults that makes an AJAX request to '/Search/GetResults' and returns the JSON-formatted data. This endpoint does not require any specific criteria to be passed. The returned data looks like this ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...

How can I achieve a smooth opacity transition without using jQuery?

Although I understand that JQuery offers functions for this purpose, I am interested in finding a solution using only pure javascript. Is there a way to change the CSS opacity setting over time? Perhaps utilizing a unix time stamp with millisecond precisi ...

How to invoke a function from a different ng-app in AngularJS

I have 2 ng-app block on the same page. One is for listing items and the other one is for inserting them. I am trying to call the listing function after I finish inserting, but so far I haven't been successful in doing so. I have researched how to cal ...

Utilizing Node.js and Express alongside EJS, iterating through objects and displaying them in a table

Today I embarked on my journey to learn Node.js and I am currently attempting to iterate through an object and display it in a table format. Within my router file: var obj = JSON.parse(`[{ "Name": "ArrowTower", "Class" ...

Struggling with the conundrum of aligning a constantly changing element amid the

I was optimistic about the code I wrote, hoping it would work out in the end. However, it seems that my expectations might not be met. Allow me to provide some context before I pose my question. The animation I have created involves an SVG element resembl ...

Creating a dynamic slideshow with automated arrow navigation is simpler than you may think

I have successfully tested the slideshow and it is functioning perfectly without any issues. I would like to have a dual slideshow setup (slideshow 1 and slideshow 2) with next and previous buttons, but I am interested in adding an automatic sliding featur ...

Guide to using Ajax to send a form and receive text in response

Check out my code on Fiddle: $("form.signupform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Added this line for reference $.post(url, data, function(data) { $(for ...

AngularJS modal not functioning properly after sending $http request

I have successfully implemented a pop-up modal in my Angular page using code from a reliable source. However, when I include a button for an HTTP request on the same page, the functionality of the AngularJS modal stops working after the HTTP request is mad ...

What is the method for designating the specific pages on which the stripejs script should be loaded?

The performance of the main-thread is being significantly impacted by Stripe's script, as illustrated in the image provided by Google Insights. https://i.stack.imgur.com/bmdJ2.png My concern is that the page currently experiencing issues does not ac ...

Enhance the appearance of TreeGrid nodes by customizing the icons according to the data within

Currently, I am working with the MUI DataGridPro component and my goal is to customize the icons of the TreeGrid nodes based on the data. This image illustrates what I hope to achieve: https://i.stack.imgur.com/nMxy9.png Despite consulting the official do ...

Having difficulty retrieving data despite providing the correct URL

I am encountering an issue with a fetch function designed to retrieve a JSON web token. Despite verifying the correctness of the URL, the function is not functioning as expected. Below is the front-end function: const handleSubmit = async (e) => { ...

Troubleshooting: JQuery - Applying CSS to dynamically generated elements

I used JQuery to dynamically generate a table, but I'm having trouble applying CSS to the columns. You can see an example at this Codepen link here. Specifically, I need to set the width of the first column to 100px. Could someone please assist me wi ...

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

Traverse through an array of pictures and add the data to a Bootstrap placeholder within HTML markup

In my quest to create a function that populates placeholders in my HTML with images from an array, I am encountering a problem. Instead of assigning each image index to its corresponding placeholder index, the entire array of images is being placed in ever ...