Change the structure of the JavaScript object into a new format

I humbly ask for forgiveness as I am struggling with figuring out how to accomplish this task. It seems like we need to utilize a map function or something similar, but I am having difficulty grasping it.

Below is the object 'data' that I am working with:

data
 [0]:
    name: 'Alex'
    sex: 'Male'
    new_joinee: false
 [1]:
    name: 'Anna'
    sex: 'female'
    new_joinee: true
 [2]:
    name: 'lester'
    sex: 'Male'
    new_joinee: true

My goal is to transform the above object into the following format:

data
name: 'Alex', 'Anna', 'lester'
sex:  'Male', 'Female','Male'
new_joinee: false,true,true

If anyone could provide guidance on how to achieve this, I would greatly appreciate it.

Answer №1

//Initializing input data
var data = [
  {name: 'Alex', gender: 'Male', new_employee: false}, 
  {name: 'Anna', gender: 'female', new_employee: true}, 
  {name: 'lester', gender: 'Male', new_employee: true}
];

//Creating output object
output = {};
for(var key in data[0]) {
   output[key] = [];
}

//Extracting data from all input objects
data.forEach(function(item){
   for(var key in item) {
     output[key].push(item[key]);
   }
});

output:

output == 
{ name: [ 'Alex', 'Anna', 'lester' ],
  gender: [ 'Male', 'female', 'Male' ],
  new_employee: [ false, true, true ] }

Answer №2

If you start with this initial set of data:

let initialData = 
[
    {name: 'Sarah', gender: 'Female', new_member: false}, 
    {name: 'Mark', gender: 'Male', new_member: true}, 
    {name: 'Emily', gender: 'Female', new_member: true}
];

You can change the structure of the data like this:

let transformed = {
    name: [],
    gender: [],
    new_member: []
};

initialData.forEach(function (item) {
    transformed.name.push(item.name);
    transformed.gender.push(item.gender);
    transformed.new_member.push(item.new_member);
});

Final Outcome:

{
    name: ['Sarah', 'Mark', 'Emily'],
    gender: ['Female', 'Male', 'Female'],
    new_member: [false, true, true]
}

Answer №3

If you are working on a project that uses underscores:

var keys = _.keys(myObj)
var foo = {
  name: _.pick(myObj, 'name'),
  sex: _.pick(myObj, 'sex'),
  newJoinee:_.pick(myObj, 'new_joinee')
}

_.each(keys, function(key) { console.log(key + ' ' + foo[key].join(', ')) })

Answer №4

Assuming that your information is stored as an array of objects

var data = convertData(data)

function convertData(data){
  var convertedData = { name: '', gender: '', newEmployee: ''};
  data.forEach(function(item){
    convertedData.name += item.name;
    convertedData.gender += item.gender;
    convertedData.newEmployee += item.newEmployee;

   });
 return convertedData;
}

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

Updating scope variables in AngularJS can be achieved inline by simply assigning a new value

Dealing with a simple issue here, utilizing AngularJS v1.7.2 with C# MVC. My setup involves Layout pages and Views. The AngularJs controllers/services are loaded from external script files, leaving the Views clean. The challenge is to assign a value from ...

Every time I attempt to send a post request, I receive back only the creation date and the unique objectID

Whenever I send a post request, only the created date and objectID are returned. Whenever I send a post request, only the created date and objectID are returned. This issue persists even after multiple attempts. I attempted to verify it using Postman ...

How to retrieve email input using SweetAlert2 in PHP?

Hello there! I'm curious about the most effective method for integrating PHP with Javascript. My goal is to execute some coding tasks once an email address has been entered. swal({ type: "success", title: "Congrats!", text: "Please enter your P ...

Top technique for verifying the presence of duplicates within an array of objects

How can I efficiently check for duplicates in typescript within a large array of objects and return true or false based on the results? let testArray: { id: number, name: string }[] = [ { "id": 0, "name": "name1" }, ...

React Grid by DevExtreme

Does anyone have a solution for adjusting the fontSize of the TableHeaderRow in a DevExtreme React Grid? Here is some code from a specific website () that I've been exploring: import * as React from 'react'; // Other imports... const Ad ...

How can methods access variables from the Vuex store during function calls?

Within my Vue.js component, there is a v-select element. Upon user selection in this widget, the toDo function is triggered from the methods block. However, when attempting to access the value of the filters getter within this function, it consistently ret ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Ensure that the flex item spans the entire width of the page

I'm struggling to make my audio-player resize properly to fit the full width of my page. I can't seem to figure out what I'm missing or doing wrong... (Current Look) https://i.sstatic.net/tEtqA.png I'm attempting to utilize HTML cust ...

Sending arrays in JSON format using Node.js Express (res.json)

I have a code snippet like this: app.get('/orders/:pizzeriaID/:status', async (req, res) => { try { const requestedOrderByPizzeriaID = req.params['pizzeriaID']; const requestedOrderByStatus = req.params['status']; ...

Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API: constructor(){ super(); this.state = {data: false} this.nextProps ={}; axios.get('https://jsonplaceholder.typicode.com/posts') ...

Is there a way to retrieve the name of a JSON or obtain the file path using NodeJS Express Router?

I've been experimenting with adding a named routers feature to the Express router for my NodeJS project. I managed to implement it successfully, but there's one thing I'm stuck on... the path. Specifically, when I have a route setup like thi ...

How can I use JavaScript to retrieve the current time from the time.nist.gov NTP server?

Looking for guidance! I'm new to coding and would greatly appreciate detailed instructions and examples. I've been struggling for hours trying to solve this issue - the online resources I found have not been helpful at all. Unfortunately, I don&a ...

The filter function in Material UI data grid does not seem to be functioning properly when using the renderCell method

I'm currently working on a react project that includes a Data Grid. While the filter functionality works well with most fields, it seems to be having issues with the field that utilizes renderCell. Is there a way to enable filtering for the movie titl ...

Ensure that the token remains current with each axios operation

I need to access an Express REST API that demands a valid json web token for certain routes. In order to include the token from localstorage every time I needed, I had to create an "Axios config file". My http.js file includes the code below: import Vue ...

Troubleshooting: Dealing with Access-Control-Allow-Origin Issue

While debugging a web app in Visual Studio 2013 Express for Web, I encountered the following error. This particular app is built with MVC using angularjs, jquery, and bootstrap. Interestingly, my other web apps are functioning without any issues and do not ...

Incorporate Object names and Variable names in Javascript programming

I have an object named res and a variable named lea. I need to concatenate. For example: let lea = "abc"; let res = { abc:'steve' }; console.log(res.lea); So my output should be steve. I tried it like this: console.log(res.`${lea}`); ...

Plugin initialization cannot occur as the $scope DOM elements are still dynamic and not ready

As I venture into the realm of AngularJS, this project marks my first deep dive into building something substantial, despite having only tinkered with a few tutorials and demos. Bear with me if I struggle to articulate what may be a straightforward questio ...

"Creating an array object in the state of Reactjs - a step-by-step

As I am delving into the world of ReactJS, I am learning about changing state within this framework. One challenge I encountered was initializing an array object in state with an unknown length and updating it later using setState. Let me share the snippet ...

Learn how to send JSON data to REST services from a webpage using the POST method, similar to how it is done in the advanced REST client

Is there a way to call restful services from a webpage and pass JSON data for the POST method, similar to what we can do in an advanced REST client? ...

Checking Whether a Value Entered in an Input Field Exists in an Array Using jQuery

Can someone help me with checking if a specific value is in my array? I want to achieve something like that, any suggestions on how to do it? if(jQuery.inArray($('#ValueInputTitle').val, variableValueInput) !== -1) { console.log("is in arr ...