Converting an Object into an Array of Objects

The question at hand is quite simple yet lacks a definitive answer. I have an object and my objective is to take each key and value pair, transform them into objects, and then push them into an array. To illustrate this, consider the example below.

{
  title: "This is a Title",
  name: "This is a name"
}

After transformation:

[
  {title: "This is a Title"},
  {name: "This is a name"}
]

Answer №1

Utilize the Object.entries method to transform the object into an array, and then employ map on the array to structure it into objects based on your desired format:

const obj = {
  type: "Example Type",
  content: "Example Content"
};

const arr = Object.entries(obj)
    .map(([key, value]) => ({ [key]: value }));

console.log(arr);

Answer №2

You have the option to transform the object's entries by selecting any entry as a reference for a new object.

const
    information = { title: "This is a Title", name: "This is a name" },
    outcome = Object
        .entries(information)
        .map(entry => Object.fromEntries([entry]));

console.log(outcome);

Answer №3

Admire the simplicity of the current solutions, but when dealing with large quantities of data, opting for a solution like the following can significantly enhance performance:

function convert(object) {
    let array = []

    for (let key in object) {
        let temporary = {}

        temporary[key] = object[key]

        array.push(temporary)
    }

    return array
}

let info = {
    title: "This is a Title",
    name: "This is a name"
}

console.log(convert(info))

Update: Finally mastered using code snippets :)

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

Consolidate code by implementing on selectmenu

I need assistance with handling multiple select menus on a View page Below is a snippet of the code: $(function() { var selectSpeed = $('#speed'), selectTest = $('#test'); selectSpeed.selectmenu(); selectTest.selectmenu() ...

What is the best approach to execute the jquery script exclusively on mobile devices?

I want to modify this code so that it only functions on mobile devices and is disabled on computers. How can I achieve this? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <ul id="pri ...

What steps should I take to link form inputs from various child components to an array that is set in a parent component?

I'm in the process of linking form input from various child components (item-input-component) to an array itemList[] that is defined in a parent component (add-invoice-component). The goal is to gather three inputs (itemName, quantity, price), create ...

The XMLHTTPRequest Access-Control-Allow-Origin allows cross-origin resource sharing to

I am attempting to send a request to a PHP file. I collect the longitude and latitude from a function in the Maps API, then use AJAX to store these points in a MySQL database. Using AJAX function savePoint(latitude, longitude){ $.ajax({ ...

Ways to simultaneously install numerous gulp packages using node-package-manager

Recently, I made the transition to using the gulp task runner for automating my workflow. However, whenever I start a new project, I find myself having to install all the required packages listed in the gulpfile.js by running the following command: npm in ...

Activate the initial tab in JQuery UI accordion upon initialization

Hello, I have implemented a simple sidenav menu on my website. It consists of parent items and child items structured according to the h3 > div format as suggested by JQuery's documentation. My challenge now is to automatically open the "active" t ...

Having trouble grasping the problem with the connection

While I have worked with this type of binding (using knockout.js) in the past without any issues, a new problem has come up today. Specifically: I have a complex view model that consists of "parts" based on a certain process parameter. Although the entire ...

Utilizing ReactJS to display a new screen post-login using a form, extracting information from Express JSON

I am facing a challenge with updating the page on my SPA application after a successful login. I have successfully sent the form data to the API using a proxy, but now the API responds with a user_ID in JSON format. However, I'm struggling with making ...

One way to clear out a directory in Node.js is to delete all files within the directory while keeping

Can anyone guide me on how to delete all files from a specific directory in Node.js without deleting the actual directory itself? I need to get rid of temporary files, but I'm still learning about filesystems. I came across this method that deletes ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Collecting data from Jitsi

After setting up a Jitsi server using packages, I am now trying to log connection statistics to a database. Specifically, I want to store data about significant bitrate changes during video calls. Although I have some familiarity with JavaScript and WebRT ...

Errors with displaying prototype function in AngularJS ng-repeat as undefined

Encountering a problem where a function is returning 'undefined' in a select field. <select name="supervisor" ng-model="editJudge.superID" ng-options="supervisor.legalProID as supervisor.fullName for supervisor in supervisors" cla ...

When the input field is clicked, the file:/// URL is sent

Currently, my HTML page contains a form that includes an input field for URLs. Ideally, upon typing in the URL and clicking the button, I intend to be redirected to that website. However, the issue lies in the fact that instead of redirecting me to the p ...

`html2canvas encountered an issue: Unable to locate a logger instance`

When I use html2canvas to render the same content repeatedly, I encounter an error about 5% of the time. It seems to be sporadic and I'm not sure why it occurs. What could be causing this unpredictable behavior? html2canvas.js:2396 Uncaught (in promi ...

What is the best way to transfer item information from Flatlist within a React Native application?

I am a newcomer to react. In my App.js file, I have the main code, and in another folder, there is a lists.js file that contains the list data. I successfully import the list from lists.js into my App.js file. Now, I want to add an onPress action to the ...

Combining the power of Kendo UI with the flexibility of Vue

Hey there everyone, I'm currently utilizing the Vue.js CLI for my project. Recently, I came across a helpful tutorial on incorporating a Jquery plugin into a webpack project at this link: . To achieve this, I installed the expose loader and added th ...

Tips for implementing both an onChange and onSubmit event for a MUI TextField

I'm currently working with React and MUI and have created a form like the following: const handleUserInput = (event) => { set_user_input(event) } const handleSubmitForm = () => { if (user_input == 'help'){ ...

How can I update the image src in JavaScript and make sure the image refreshes properly?

I managed to update the image source in JavaScript code, changing it from: http://loclhost:8080/mvc/resources/pics/625bd317-b71c-4d74-aff2-248b86ff900b.jpg to http://loclhost:8080/mvc/resources/pics/4c1541ab-204c-4eff-b641-8527294e02cd.jpg Here is the ...

Tips on using the Unix "paste" command in Node.js without the need to load entire files into memory

Implementing the basic Unix paste command in Python is straightforward, as shown in the following snippet (which currently processes two files, unlike Unix paste that can handle multiple files): def pasteFiles(file1, file2): with open(file1) as f1: w ...

Is the button inactive until an action is taken?

In my coding project, I am working with two buttons. I am trying to figure out a way to disable the second button until the first button is clicked. Does anyone have any suggestions on how to achieve this using a combination of JavaScript and CSS? ...