Restructure an array of objects into a nested object structure

I have a list of task items that I need to organize into a structured object based on the ownerID

var tasks = [
{taskID: "1", title: "task1", ownerID: "100", ownerName: "John", allocation: 80},       
{taskID: "2", title: "task2", ownerID: "110", ownerName: "Sarah", allocation: 50}, 
{taskID: "3", title: "task3", ownerID: "110", ownerName: "Sarah", allocation: 50}, 
{taskID: "4", title: "task4", ownerID: "120", ownerName: "Mike", allocation: 25},
{taskID: "5", title: "task5", ownerID: "120", ownerName: "Mike", allocation: 45}];

This is the desired structure:

var people = {

    100: { 
        ownerName: "John",
        tasks: [      
            {taskID: "1", title: "task1", allocation: 80}
        ]       
    },

    110: {
        ownerName: "Sarah",
        tasks: [
            {taskID: "2", title: "task2", allocation: 50},
            {taskID: "3", title: "task3", allocation: 50}
        ]       
    },

    120: {
        ownerName: "Mike",
        tasks: [
            {taskID: "4", title: "task4", allocation: 25},
            {taskID: "5", title: "task5", allocation: 45}
        ]       
    }
};


I am iterating through the original data and assigning each entry

people[ownerID] = {};
person = people[ownerID];
person['ownerName'] = ownerName;
person['tasks'] = [];
person[taskID] = {};
task = person[taskId];
task['taskID'] = taskID;

The current setup groups by ownerID correctly but only includes one task per individual.

Please assist. Thank you!

Answer №1

Here is an effective method to achieve this (assuming ownerName is functionally dependent on ownerID):

const tasks = [   
  {taskID: "1", title: "task1", ownerID: "100", ownerName: "John", allocation: 80},       
  {taskID: "2", title: "task2", ownerID: "110", ownerName: "Sarah", allocation: 50}, 
  {taskID: "3", title: "task3", ownerID: "110", ownerName: "Sarah", allocation: 50}, 
  {taskID: "4", title: "task4", ownerID: "120", ownerName: "Mike", allocation: 25},
  {taskID: "5", title: "task5", ownerID: "120", ownerName: "Mike", allocation: 45}];

const result = tasks.reduce( (acc, {taskID, title, ownerID, ownerName, allocation }) => {
    (acc[ownerID] = acc[ownerID] || { ownerName, tasks: [] })
        .tasks.push( { taskID, title, allocation } );
    return acc;
});

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

Answer №2

users[userID] = {};

user['jobs'] = {};

This code snippet fails to verify if an object with the identical key already exists, resulting in the creation of a new object every time.

To address this issue, consider modifying it as follows:

users[userID] = users[userID] || {};

user['jobs'] = user['jobs'] || {};

Answer №3

It's important to note that tasks should be structured as an array, as objects are unable to contain other objects without a key.

var tasks = [   
{taskID: "1", title: "task1", ownerID: "100", ownerName: "John", allocation: 80},       
{taskID: "2", title: "task2", ownerID: "110", ownerName: "Sarah", allocation: 50}, 
{taskID: "3", title: "task3", ownerID: "110", ownerName: "Sarah", allocation: 50}, 
{taskID: "4", title: "task4", ownerID: "120", ownerName: "Mike", allocation: 25},
{taskID: "5", title: "task5", ownerID: "120", ownerName: "Mike", allocation: 45}];

var transformed = tasks.reduce((obj, item)=> {
    if(!obj[item.ownerID]) {
        obj[item.ownerID] = {};
    }
    obj[item.ownerID].ownerName = item.ownerName;
    if(!obj[item.ownerID].tasks) {
        obj[item.ownerID].tasks = [];
    }
    obj[item.ownerID].tasks.push({taskID: item.taskID, title: item.title, allocation: item.allocation})
    return obj;
}, {})
console.log(transformed);

Answer №4

To set a default operator and assign a new object if the property is missing, you can use the logical OR.

var tasks = [{ taskID: "1", title: "task1", ownerID: "100", ownerName: "John", allocation: 80 }, { taskID: "2", title: "task2", ownerID: "110", ownerName: "Sarah", allocation: 50 }, { taskID: "3", title: "task3", ownerID: "110", ownerName: "Sarah", allocation: 50 }, { taskID: "4", title: "task4", ownerID: "120", ownerName: "Mike", allocation: 25 }, { taskID: "5", title: "task5", ownerID: "120", ownerName: "Mike", allocation: 45 }],
    people = {};

tasks.forEach(({ taskID, title, ownerID, ownerName, allocation }) => {
    people[ownerID] = people[ownerID] || { ownerName, tasks: {} };
    people[ownerID].tasks[taskID] = people[ownerID].tasks[taskID] || { taskID, title, allocation };
});

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

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 it necessary to have both Express and express-generator in my toolbox?

Recently delving into the world of node.js and stumbled upon express; While browsing the npm repository site https://www.npmjs.com/package/express, I noticed that the installation process is clearly stated as: $ npm install express However, further down ...

Tips for creating equal height columns in Bootstrap 4

Working with Bootstrap 4 Beta in an attempt to create two columns that maintain full height regardless of screen size. The code below functions perfectly, ensuring both columns maintain full height across all devices. However, upon inserting the bootstra ...

JSON parsing partially successful: sub-object is empty

Attempting to parse a json file, my initial try with a simplified version was only partially successful. The simplified json structure resembles the following: { "rowCount": 102, "data": [ {"id": "56" ...

What is the best way to transform each row of a dataframe into JSON format using R?

I have a DataFrame named df1, where the 'array' column contains JSON arrays. df1 <- data.frame(email = c('user1', 'user2', 'user3', 'user4'), date = c('2021.07.07', '2021.07.07', &apo ...

What Causes the Misalignment Between My Image and Text?

I am trying to randomly select a slide from the list of slides when the page loads, and then display it in the hero section of a website. However, I am facing an issue where the Image seems to be out of sync with the Text & Button (for example, displaying ...

What are the steps to create a project template in WebStorm by saving an existing project?

Currently, I am working on my Express.js project in WebStorm 8 and I would like to save it as a project template. Can you please guide me on how to do this using WebStorm? ...

Generating HTML content from XML data with the help of JavaScript

Challenge: Attempting to display one question and its four corresponding answers at a time from an XML file. JavaScript code: var xmlDoc, quest, ans, i, n; xmlDoc = loadXMLDoc("questions.xml"); quest = xmlDoc.getElementsByTagName('main'); do ...

Reduce the density of x-axis labels in highcharts

Do you have any input on Highcharts? This chart belongs to me: I am looking to reduce the density of x-axis labels, similar to the y-axis. Your assistance is greatly appreciated. Edit: for instance, take a look at this example: http:// jsfiddle.net /vu ...

Seeking the location of the `onconnect` event within the Express framework

With the use of "express," I have implemented a middleware function like so: app.use(function(request, response, next) { console.log(request.headers["user-agent"]); // etc. }); This currently displays the user-agent header in the console for ever ...

Why is the result displaying as 0 instead of 0.0?

After declaring an array of 10 elements and initializing it with values ranging from 0.0 to 9.9, I encountered an issue where the output displayed 0 instead of 0.0. Can anyone explain why this is happening? #include <iostream> using namespace std; i ...

Rotate each row of the table in sequence with a pause between each flip

I have a table with 3 columns and 10 rows. I would like to flip each row one by one, where each row contains data on both the front and back sides. The flipping animation should be similar to the example provided in this link, but the flipping should sta ...

Transform a string into an object

How can I convert a string into an object with error details? const er= {'username': [ErrorDetail(string='A user with that username already exists.', code='unique')], 'email': [ErrorDetail(string='user with thi ...

Display and conceal multiple div elements using a timer

Currently, I am working on creating a message box that will display active messages one by one from a MySQL table. The challenge is that the number of divs needed can vary depending on the number of active messages in my database. Using an ajax timer and P ...

How to efficiently deliver a document to a user using the MEAN stack

The express controller code snippet I'm working with involves creating a CSV file and sending it back to the user: // Correct file path and write data var currentDate = new Date(); var storagePath = path.join(__dirname,'../../public/reports/&apo ...

What is the syntax for defining parameters in an overloaded arrow function in TypeScript?

Trying to create an async arrow function that can handle a single image object or an array of image objects. I'm new to TypeScript overloading and may be approaching this the wrong way. Here's what I've come up with: type ImageType = { ...

I'm looking for a way to set up a PropType that accepts a boolean value, but also allows for

Currently, my code includes a Modal component with a prop called disableEscapeKeyDown. The PropType defines it as boolean | null, but when trying to use it in the ModalWindow function, I receive an error stating Type 'boolean | null' is not assig ...

How can I create clickable table entries using php and html?

I want to create a table on this page that is clickable. When the user clicks on a row, the data from that row will be sent to a PHP file with a form prepopulated with the selected user's information for updating purposes. <!DOCTYPE html> &l ...

Favicon not appearing on Jekyll website

This is my first time working with Jekyll. I'm currently working on localhost and trying to set a favicon for the website. I generated the image.ico and added the code provided to my head.html file. The image appears in my _site folder, but it's ...

Any ideas on resolving the NPM EJSONParse error in my package.json file?

Upon setting up auto scripts and installing necessary packages to streamline my tasks, I encountered the following error: npm ERR! file C:\Users\windw\Desktop\bootstrap4\package.json npm ERR! code EJSONPARSE npm ERR! JSON.parse Fai ...

Model updating with the addition of an item and triggering a secondary ng-repeat for refreshing

As I was working on the phone tutorial, I found myself pondering how to implement a specific use case. The browser renders a list of phones. When the user clicks on add phone for one of these phones, the function addItem is triggered and adds that phone ...