Convert a JavaScript array of objects into an array of arrays

I'm searching for a more elegant ES6 solution to transform this array:

var src = [{x:1,y:'a'},{x:2,y:'b'}];

Into this array:

var desc = [[1,2],["a","b"]];

This new array should contain one array for all properties and another array for all values.

Here is the code I currently have:

var src = [{x:1,y:'a'},{x:2,y:'b'}];

var prop1 = [];
var prop2 = [];

src.forEach(item => {
    prop1.push(item.x)
    prop2.push(item.y);
});

var desc = [prop1, prop2];

While it works well, it feels lengthy. So, any suggestions for improvement with shorter code would be appreciated.

Answer №1

You can customize the order of props (since the order of keys in an object is not guaranteed) and then iterate over the src array to extract the corresponding prop value.

var src = [{x:1,y:'a'},{x:2,y:'b'}]

var props = ['x', 'y'];

var result = props.map(prop => src.map(x => x[prop]))

console.log(result)

Answer №2

To achieve this, you can leverage the power of .reduce() method:

let data = [{x: 1, y: 'a'}, {x:2, y: 'b'}];

let output = data.reduce((accumulator, currentValue) => (accumulator[0].push(currentValue.x), accumulator[1].push(currentValue.y), accumulator), [[], []]);

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

Additional Documentation:

Answer №3

One approach is to loop through the array and iterate over the keys of each object, swapping the outer and inner indices for the target element.

var src = [{ x: 1, y: 'a' }, { x: 2, y: 'b' }],
    desc = [];

src.forEach(o => Object.keys(o).forEach((k, i) => (desc[i] = desc[i] || []).push(o[k]));

console.log(desc);

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

Ways to separate my json object into multiple variables

I am looking to extract the following data: name, meetup, tag from my object and store them in separate variables or objects. Here is my json object: var data = { "MY_ID": 1, "module": [ { "name": "Manch ...

Obtaining data from HTML input in Flask while dynamically altering the website's URL

I have a text box in my HTML code and I am trying to figure out how to retrieve the data that is entered into that box when a button is clicked. I have experience getting data from a form using the code snippet below: ex = request.form['example' ...

The Incompatibility of C Pointers and Arrays: Understanding the Differences

Can someone help me understand why I am unable to perform this action? int main(int argc, char **argv){ FILE *src; char filePath[261]; filePath = argv[1]; The final line is causing a compilation error. What distinguishes char[] from char*? H ...

Incorrect format for a date in AngularJS

I have a time input field where I am receiving the date and time format 'Thu Jan 01 1970 12:59:00 GMT+0530 (India Standard Time)', but I only want to display the time. Is there an issue with the time picker in AngularJS? Can anyone help me resolv ...

Show validation messages using ng-messages depending on various conditions

Implementing angular ng-messages for validation message display Check out this code snippet: <ul ng-messages="formToValidate.fieldToValidate.$error" ng-messages-multiple> <li ng-message="pattern">Invalid pattern</li> <li ng-m ...

Execute a node script file at random intervals

I've been utilizing forever to maintain the continuous execution of a node script: forever start script1.js However, my requirement is to run these files in a random order... For instance: Execute node script1.js Execute node script2.js Run script ...

Acquire the key name of an object during iteration in Jade

const information = { attribute1: 'value1', attribute2: 'value2', attribute3: 'value3' }; for each value, key in information li= value.keyname?? The desired result should be: <li>attribute1</li> <li ...

Infinite Array Length in Visual Basic .NET

Creating a 2D Infinite array. Here is my code snippet: Dim array As String(,) = New String(,) {} array(0, 0) = "top left" MsgBox(array(0, 0)) However, the MsgBox is not displaying anything. ...

javascript conceal a div when clicked elsewhere

I am trying to implement two JavaScript functions: 1) Displaying a DIV (welcomeDiv) when clicking on a button; 2) Hiding the div by clicking outside of 'welcomeDiv' container. function showDiv() { document.getElementById('welcomeDi ...

Although my ajax request was unsuccessful, I was able to successfully upload my post

Why is my ajax request failing while still uploading my post? How can I prevent this failure? Here is my ajax request code: createRate(){ var ourNewPost = { 'title': $(".new-rate-title").val(), 'content': $('. ...

Inject some content into the page with the power of jQuery

Currently working with jQuery, I have a div containing H2 tags. <div id="preload"><h2></h2></div> I'm looking to understand how to use jQuery to insert text inside the <h2> tags The expected outcome should be: <div ...

What is the answer to this issue where the entity name is required to directly come after the "&" in the entity reference?

Whenever I insert the code into my Blogger platform, an error pops up stating: The entity name must directly follow the '&' in the entity reference Here is the code: <script> if (typeof bc_blocks == "undefined" && wind ...

Creating an array in Javascript and populating it with dynamically generated values

I am currently iterating through 3 arrays, searching for 'actionTimings' in each array and summing up the values of actionTimings (which are all numbers). How can I store these 3 values in a new array? This is what I have tried so far... $.each( ...

Check if the page has been loaded using Jquery

Can anyone share a helpful strategy for initiating a function in JavaScript that only begins once the entire page has finished loading? ...

Tips on retrieving values from input files using jQuery

Is there a way to retrieve the value of an input type using jQuery? Specifically, when I add a file to the input file, I want to dynamically add more input types with the file's value. Currently, I am using the following code: $('#show_input&apo ...

Rotating images with React

I am encountering an issue with implementing an image carousel in React. Previously, it worked perfectly when I was not using React, but now that I am migrating the page, I am facing an error. ** The carousel is located on the home page: ** const Home = ( ...

Developing a function that can handle an array containing interface instances

Hey there, I've encountered a bit of a puzzle with this assignment. The first part was all good; creating an interface and using it in different classes. But now I'm stuck on the second part which seems to be throwing me off with its logic. It al ...

How to create a blinking effect for buttons in an Angular app with ng-if or ng-show

I've come across the same issue in two separate angular projects I've been involved with, but have not been able to find any discussion on this particular problem. This leads me to believe that there may be something I am overlooking. Let's ...

What is the best way to retrieve an item using a composite key?

const dynamoDB = new AWS.DynamoDB.DocumentClient(); var parameters: any = {}; parameters.TableName = 'StockDailyCandles'; var primarykey = { 'symbol': 'AAPL', 'datetime': '640590008898' }; // sa ...

Having difficulty entering text in the modal text box and updating it with a new state

Within my render method, I am utilizing the following model: { showEditModal && <Modal toggleModal={this.togglePageModal} pageModal={true}> <h2 style={{ textAlign: "center", width: "100%" }}> ...