Convert an array of objects into an array of objects with combined values

Here is an example of an array containing objects:

 array = [
{prop1: 'teste1', prop2: 'value1', prop3: 'anotherValue1' },
{prop1: 'teste2', prop2: 'value2', prop3: 'anotherValue2' },
{prop1: 'teste3', prop2: 'value3', prop3: 'anotherValue3' }

]

I am looking to transform this array into a new format like below:

[
   {prop1:['teste1', 'teste2', 'teste3']},
   {prop2:['value1', 'value2', 'value3']},
   {prop3:['anotherValue1', 'anotherValue2', 'anotherValue3']}
]

Answer №1

To retrieve the keys from the first object in the array, you can use the Object.keys method on array[0]. Then, you can leverage the map function to create a new object with these keys and apply the spread operator along with the reduce method to merge the previous and current values in your array.

const myArray = [
  { name: 'John', age: 30, city: 'New York' },
  { name: 'Sarah', age: 25, city: 'San Francisco' },
  { name: 'Mike', age: 35, city: 'Chicago' }
];

 const transformedArray = Object.keys(myArray[0]).map(key => ({
    [key]: myArray.map(obj => obj[key])
 }));

console.log(transformedArray)

Answer №2

const data = [{
  name: 'John',
  age: 30,
  city: 'New York'
}, {
  name: 'Jane',
  age: 25,
  city: 'Los Angeles'
}, {
  name: 'Alice',
  age: 35,
  city: 'Chicago'
}];

const output = Object.values(data.reduce((acc, obj) => {
  Object.entries(obj).forEach(([key, value]) => {
    acc[key] = acc[key] || {
      [key]: []
    };
    acc[key][key].push(value);
  });
  return acc;
}, {}));

console.log(output);

You can utilize the reduce method to obtain the desired outcome.

Answer №3

One approach is to group the entries by key and create an object from those entries to form the result set.

const
    data = [{ prop1: 'test1', prop2: 'value1', prop3: 'anotherValue1' }, { prop1: 'test2', prop2: 'value2', prop3: 'anotherValue2' }, { prop1: 'test3', prop2: 'value3', prop3: 'anotherValue3' }],
    result = Object
        .entries(data.reduce((r, o) => {
            Object.entries(o).forEach(([k, v]) => (r[k] ??= []).push(v));
            return r;
        }, {}))
        .map(p => Object.fromEntries([p]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

Within this scenario, the initial loop will cycle through all the keys while the subsequent loop will iterate over every object associated with that specific key.

const array1 = [
    {prop1: 'test1', prop2: 'value1', prop3: 'anotherValue1' },
    {prop1: 'test2', prop2: 'value2', prop3: 'anotherValue2' },
    {prop1: 'test3', prop2: 'value3', prop3: 'anotherValue3' }
]

let array2 = []
Object.keys(array1[0]).forEach(function(data){
    let obj = {};
    obj[data] = []
    array1.forEach(item => obj[data].push(item[data]))

    array2.push(obj)
})

console.log(array2)

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

Is the JavaScript Base64 image data damaged or compromised?

My current task involves selecting an image through an HTML Input and then retrieving the image using Javascript to obtain its Base64/Image Data string. However, the code I have implemented is only returning a partially corrupt or invalid representation o ...

Ensuring Secure API Request Distribution

Currently, I am experimenting with distributed API requests. In PHP, I am developing a website that allows users to make requests on behalf of the server. The objective is to distribute these requests among users to maintain scalability even in high-traffi ...

Is it possible to utilize Angular's $http.get method with a dynamic route

I recently started working with Angular and I'm trying to figure out how to retrieve data from a REST API using a scope variable to determine the URI for the GET request. Imagine that I have an array of numbers being generated by a service in my app ...

Unable to trap error using try-catch block within an asynchronous function

I'm attempting to integrate a try-catch block into an async function, but I am having trouble catching errors with status code 400 using the code below. const run = async () => { const response = await client.lists.addListMember(listId, { ema ...

Click to shift the div downwards

Currently, I have a piece of javascript applied to a div that directs the user to a specific link: <div style="cursor:pointer;" onclick="location.href='http://www.test.com';"> I am wondering if there is a way to add an effect where, upon ...

Creating a dynamic nested list in HTML using JavaScript with data retrieved from a JSON source

I'm trying to generate a dynamic nested ul\li list from a JSON array. IMPORTANT! While I can use jQuery for this transformation, it's in a node.js environment where DOM access is restricted and I must work with a string. The depth of the a ...

Tips for efficiently moving through divs in a personalized single page application?

Exploring the world of JS frameworks and single page app functionality is a bit of a mystery to me. Currently, I have a pseudo single page app set up without any specific framework in place. The setup involves 3 tabs that toggle visibility for 3 different ...

Update HTML element using Jquery periodically

I have a PHP script that updates me with the upcoming bus departure time. Currently, I am using jQuery to refresh this information in a div every minute. However, since I know when the data will change (after the bus arrives), I want the div to refresh at ...

Angular is throwing an error because it cannot find the definition for

Embarking on a tutorial journey to dive into Angular setup. Facing a persistent error in my code... Error: [$injector:undef] http://errors.angularjs.org/1.6.0/$injector/undef?p0=Bear Listing the order of files within the <head> tag in the html ...

Retrieving data from a remote PHP server using JavaScript

I am currently working on two separate websites. Site A is coded using only HTML and JavaScript, while site B utilizes PHP. I am trying to figure out a way to access variables from site B within site A. For example: The code for site A looks something li ...

Display loading spinners for multiple ajax requests

At the moment, I am displaying spinners using the ajax setup method call: (function() { $.ajaxSetup({ beforeSend: showLoader, complete: hideLoader, error: hideLoader }); })(); While this setup is functioning properly, the ...

What is the best way to verify the presence of # in a URL?

Every now and then, due to caching issues, I find myself adding a # to my URL, like so: http://www.example.com/#lang=3201954253 My goal is to find and remove the #lang from the URL if it is present. ...

Before clicking the submit button, send field values using Ajax

Is it possible to send values using ajax before submitting form data with a submit button? I have the code below. It successfully reaches the success function, but I am unable to retrieve the posted data. Any ideas on how to solve this issue? Your help an ...

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

What is the process for verifying a particular user in AngularJS?

I'm new to AngularJS and I'm a bit confused about the concepts of GET, PUT requests. I am currently working on an app where I display a list of users on one page, and on another page, I have a form with three buttons. My main focus is on the "Con ...

Issue with multiple dropdown menus not closing when clicked on

The current implementation provides the functionality to convert select boxes into list items for styling purposes. However, a drawback of the current setup is that once a dropdown is opened, it can only be closed by clicking on the document or another dr ...

Tips on leveraging dynamic queries in your REST API usage

As a new Javascript learner, I am experimenting with creating a basic rest api using node.js. Currently, I have set up a database called testDb and a table named testMeasurement in influxdb. The testMeasurement table consists of the columns DateOfBirth, ID ...

To ensure the smooth functioning of a React application running on a Docker container in Ubuntu 16.04, it is

I'm currently in the process of setting up a docker container for running a react app that sends a fetch request to another docker container containing a node server. The deployment is on Ubuntu 16.04, however, after building and deploying the contain ...

The jsPDF tool captures only the visible frame in a screenshot instead of printing the entire content on the screen

Recently, I integrated the jsPDF npm module into my Angular application to convert HTML to PDF. However, I encountered an issue where printing a website page to PDF only captures a screenshot of the visible area in Firefox and Chrome, as well as in Interne ...

Extension for Firefox: Unable to access variables or functions from the movie_player element on YTMusic

Looking to develop a Firefox extension for hosting "Yt-Music parties" where users can sync up with the host YtMusic. The "movie_player" element houses various functions and variables that could be valuable, such as the current song time. Strange enough, ...