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 there a way to incorporate timeouts when waiting for a response in Axios using Typescript?

Can someone assist me in adjusting my approach to waiting for an axios response? I'm currently sending a request to a WebService and need to wait for the response before capturing the return and calling another method. I attempted to utilize async/aw ...

"Looking to retrieve data from an array instead of an object in JavaScript? Here's how you can

There is a slight issue with my fetch method in grabbing data from this link . I am attempting to use the .map function on it but instead of functioning properly, I encounter an error that says Unhandled Rejection (TypeError): jedis.map is not a function. ...

Unable to find the import "@mui/x-charts/PieChart" in the file "src/components/Pie/Pie.jsx". Could the file be missing or spelled incorrectly?

I utilized the PieChart component in my pie.jsx file pie.jsx import { PieChart } from '@mui/x-charts/PieChart'; const Pie = () => { return ( <div> <PieChart series={[ { data: [ ...

Retrieving hashtags from a text

If I had a string like this var feedback = "Yum! #yummy #delicious at #CZ" Is there an efficient way to extract all the hashtags from the string variable? I attempted using JavaScript's split() method, but it seems cumbersome as I have to repeate ...

Unable to retrieve data from PHP using AJAX request

My project consists of 3 interconnected files: index.php, functions.js, and compute.php In index.php, there is a div that triggers a function in functions.js called compute(), which sends an AJAX request to perform a task in compute.php The code in index ...

Convert the entirety of this function into jQuery

Can someone please help me convert this code to jQuery? I have a section of jQuery code, but I'm struggling with writing the rest! function showUser(str) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Is it possible for the client to prevent the blocking of the Cross-Origin Resource Sharing (CORS) error?

I am encountering an issue with my web app that involves CORS operations when making $.getJSON AJAX calls. Typically, this functions properly on most client browsers due to the server having CORS enabled. However, I recently discovered that when using IE 1 ...

When attempting to upload a file using ajax, the $_FILES variable in PHP came

I am facing an issue with uploading images via AJAX where my PHP is not receiving the AJAX post. function handleFileSelect(evt) { files = evt.target.files; // FileList object $('.thumb-canvas' + filesId).css('display','bl ...

Creating a transcluding element directive in AngularJS that retains attribute directives and allows for the addition of new ones

I've been grappling with this problem for the past two days. It seems like it should have a simpler solution. Issue Description The objective is to develop a directive that can be used in the following manner: <my-directive ng-something="somethi ...

Next.js: Uh-oh! Looks like we've hit an obstacle with Error 413 Request Entity

I've encountered an issue while attempting to upload large files using Next.js. I've set up an onChange function for my file input, and here's the code snippet: const handleFileUpload = () => new Promise(async (resolve) => { if(ref ...

Instructions on integrating a column of buttons into a Bootstrap table containing information retrieved from a MySQL database

My bootstrap table is currently displaying data that is loaded from a MySQL database. I am looking to enhance it by adding a column with buttons, similar to the layout shown in this image. https://i.stack.imgur.com/8fWfR.png However, I am facing some dif ...

Access the JSON data stored in the File Directory by reading and utilizing it for your project

Can someone help me figure out how to retrieve data from the xmltojson.json file and assign it to a variable using JavaScript? const jsonfile = require('jsonfile') const file = 'xmltojson.json' jsonfile.readFile(file, function (err, obj ...

Is it possible to make the entire div clickable for WordPress posts, instead of just the title?

I am currently facing an issue where only the h1 element is linked to the post, but I want the entire post-info div to be clickable. Despite my efforts, I haven't been able to make the whole div clickable, only the h1 element remains so. Below is the ...

Discover the method for inserting a title attribute value into a span element

Utilizing AngularJS to retrieve and display data within a span element. I am now aiming to utilize this value as the title for another span element. The current code being used is shown below: <span style="display: inline-block; width: 160px">{{acti ...

Using Selenium Webdrivers to Browse Pages with Minimal Resource Loading

I'm attempting to restrict Javascript from altering the source code of the site while testing with Selenium. Disabling Javascript completely in the Webdriver is not an option as I require it for testing purposes. Below is my approach for the Firefox W ...

Leveraging IPFS to host a CSS stylesheet

I've been trying to load a css stylesheet using this link... I attempted adding the link tag to both the main and head tags. <link type="text/css" rel="stylesheet" href="https://ipfs.io/ipfs/Qmdun4VYeqRJtisjDxLoRMRj2aTY9sk ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

Is the Date Epoch a reliable form of unique identification?

Currently, I'm developing a Node API and encountered a situation where I need to create a unique 15-digit random number for a model without using autoincrement. The challenge is to ensure that the generated number is not trivial. I am hesitant about ...

Ways to resolve a 500 internal error

I have created an online test system for students, but I am facing an issue with passing answers in JSON format. Whenever I attempt to do so, I encounter a 500 internal error and I am unable to identify the root cause. Even after removing lengthy JSON dat ...

Utilizing the Power of GrapesJs in Vue3

Recently, I attempted to integrate the GrapesJS editor into my Vue.js project, but encountered some difficulties. The editor was not visible in the browser, and the designated tag for the editor appeared empty. Here is my editor configuration: <template ...