Ways to evaluate two objects and update the key identifier?

Compare the keys in the headerObject with the keys in dataObj and create a new object using the labels from headerObject.

const headerObject = [{
    label: 'Code',
    field_key: 'code'
  },
  {
    label: 'Worked Accounts',
    field_key: 'workedAccounts'
  },
  {
    label: 'Contactable Accounts',
    field_key: 'contactableAccounts'
  },
  {
    label: 'Taken By',
    field_key: 'takenBy'
  },
];

const dataObj = [{
    "code": "ABCD",
    "takenBy": "",
    "workedAccounts": 4,
    "contactableAccounts": 3,
  },
  {
    "takenBy": "Ram",
    "workedAccounts": 2,
    "contactableAccounts": 1,
  },
  {
    "takenBy": "krish",
    "workedAccounts": 2,
    "contactableAccounts": 2,
  },
  {
    "code": "XYZ",
    "takenBy": "",
    "workedAccounts": 9,
    "contactableAccounts": 4,
  },
  {
    "Taken By": "Jack",
    "workedAccounts": 5,
    "contactableAccounts": 0,
  },
  {
    "Taken By": "krish",
    "workedAccounts": 4,
    "contactableAccounts": 4,
  }
];

const result = [{
    "Code": "ABCD",
    "Taken By": "",
    "Worked Accounts": 4,
    "Contactable Accounts": 3,
  },
  {
    "Taken By": "Ram",
    "Worked Accounts": 2,
    "Contactable Accounts": 1,
  },
  {
    "Taken By": "krish",
    "Worked Accounts": 2,
    "Contactable Accounts": 2,
  },
  {
    "Code": "XYZ",
    "Taken By": "",
    "Worked Accounts": 9,
    "Contactable Accounts": 4,
  },
  {
    "Taken By": "Jack",
    "Worked Accounts": 5,
    "Contactable Accounts": 0,
  },
  {
    "Taken By": "krish",
    "Worked Accounts": 4,
    "Contactable Accounts": 4,
  }
];

result = filter(headerObj, el =>
    Object.keys(dataObj)?.filter(ele => ele === el.field_key && {[el.field.key]: ele[field.key));

Answer №1

const taskArray = [
    {
        name: 'Task 1',
        category_key: 'category1',
    },
    {
        name: 'Task 2',
        category_key: 'category2',
    },
    {
        name: 'Task 3',
        category_key: 'category3',
    },
    {
        name: 'Task 4',
        category_key: 'category4',
    },
];

// Here is the initial structure of the task array
// that you should aim for
const taskMap = taskArray.reduce((acc, { name, category_key }) => {
    acc[category_key] = name;
    return acc;
}, {});

const dataTasks = [
    {
        category1: 'Assignee',
        category2: 'Status',
        category3: 'Priority',
    },
    {
        category2: 'In Progress',
        category3: 'High',
    },
    {
        category2: 'Completed',
        category3: 'Low',
    },
    {
        category1: 'User',
        category2: 'Pending',
        category3: 'Medium',
    },
    {
        category1: 'Admin',
        category3: 'Low',
    },
    {
        category1: 'User',
        category2: 'Active',
        category3: 'High',
    },
];

const summary = dataTasks.map((obj) => {
    return Object.fromEntries(Object.keys(obj).map((key) => [taskMap[key], obj[key]]));
});

console.log(summary);

Answer №2

Your example objects contain some errors, but I believe this code snippet addresses your needs:

const mapObject = headerArray.reduce((accumulator, item) => ({...accumulator, [item.field_key]: item.label}), {});

dataArray.reduce((accumulator, item) => [
  ...accumulator,
  Object.keys(item).reduce((current, key) => ({ ...current, [mapObject[key]]: item[key] }), {})
], []);

In the beginning, creating a mapping object for easier comparison of keys and values is essential before proceeding with the mapping process. Hopefully, this solution proves helpful to you.

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

Filtering Out Elements from an Array with the Filter Method

How can I efficiently remove all elements from an array that match the values of subsequent unknown arguments? Here's my current approach: function destroyer(arr) { var arrayOfArgs = []; var newArray = []; for (var i = 0; i < arguments ...

Encountering a Basic React Issue: Unable to Implement @material-ui/picker in Next.js

I'm currently attempting to integrate the @material-ui/pickers library into my Next.js application. In order to incorporate the Picker provider, I followed the guidance provided in the Next.js documentation by adding the _app.js file inside /pages: i ...

Ending a timed function in AngularJS 1

As part of my Angular JS 1 learning journey, I am working on a small test involving text areas that display text using Angular functions when a user enters and exits them. The enter function has a 3-second delay, while the exit function waits for 5 seconds ...

Is it possible to dynamically group by one column in a dataset without requiring a trigger function?

I've been working on a script that retrieves values from another page and organizes them into a table alphabetically by Name, City, and District. The current script is functioning well, but I now want to enhance it by grouping the values by city as we ...

Unable to link to 'Attribute A' because it is not recognized as a valid property of 'Subcomponent'

Within my project, I have a generic class with several components that inherit from it. BaseRdnInput.ts: @Injectable() export abstract class BaseRdnInput implements ControlValueAccessor, Validator { @Input() rdnModel?: any | Array<any ...

Is it possible to utilize TypeScript for enforcing type safety in AngularJS templates?

Is it possible to utilize TypeScript in Angular 1.6 templates, following best practices such as components/bind-to-controller usage? Consider the following template code: <div>{{$ctrl.children[0].name}}</div> If we know the type of the contr ...

Bootstrap Popover not displaying information after an AJAX request

I'm struggling to update the popovers contents with Ajax result in my ASP.Net MVC4 project. Using ASP.Net (MVC4): public ActionResult GetEmployeeDetails(string employeeId) { var contract = UnitOfWork.ContractRepository.ContractBu ...

The functionality of updating the logo in the browser tabs is not functioning as expected in Vue.js 3

This is the code from my index.html: <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE ...

spill the elements from one div into another div

I'm facing a situation where I have 2 divs on a page, with the first div containing text content only. The issue is that when the content of the first div overflows, it gets cut off due to the CSS applied to it: .one { overflow: hidden; width: 1 ...

What could be causing my newsletter form to malfunction on Amazon CloudFront?

I'm currently working with HTML on an Amazon EC2 instance (Linux free tier). I want to integrate CloudFront into my setup, but I'm encountering issues with my newsletter functionality. Despite not being an expert in AWS, I am struggling to unders ...

Creating a JavaScript class that mimics the behavior of a C# class/object and can be seamlessly used in a Vue component

I am looking to develop a unique Javascript class that can be instantiated from a Vue component and have functions called on it similar to how it is done in C#. public class MyCustomClass() { public MyCustomClass(string someParameter){ .... ...

Displaying images using <img src='path' /> in React is causing some troubles

I'm currently working on a React template for the front page and I need to display various local dummy images. Within my <Main /> component, I import other components that pass the image path as a parameter, like this: <Container type ...

Combine an unlimited number of arrays in Node, arranging the items in the result array in an alternating pattern

How can I efficiently merge multiple arrays of different lengths containing objects of the same types into one final array while ensuring that the items alternate in the result? For example, if one array only has one value, the merging should continue alt ...

Ionic - encountering crashes with ion-nav-view on emulator

I am encountering an issue with ion-nav-view. Whenever I try to use it, the emulator displays a black screen, but it works perfectly fine in ionic serve. I suspect it may be a syntax error causing this problem. Interestingly, when I create a blank projec ...

Attempting to deploy an Angular 9 web project within Visual Studio

Starting my first Angular project has been a smooth process so far. After successfully running "npm start" without any errors, I encountered some issues when launching the application from Visual Studio. Despite sending the same commands, I consistently ...

Modify the cssclass of a button within a datalist by utilizing JQuery in an ASP.NET environment

I need to change the CSS of one button when another button is clicked within a datalist using jQuery. On my page, I have multiple images and my code only allows one "like" to be selected. I need to be able to differentiate which one I have chosen. Here i ...

Ways to enable dragging for dynamically generated elements using gridstack

Within my project, I have incorporated a drag and drop library known as gridstack. For more information, you can refer to their documentation on github here. An issue arises when statically adding elements into the DOM and initializing gridstack, as thes ...

Angular and Firebase: Incorporating user feedback into the frontend data structure

I am new to using Angular and Firebase. My current approach involves logging in with Angular to my Firebase backend and then viewing the response in the console to see all the keys associated with a firebase user. However, I am looking for a way to link th ...

The act of searching for items within a table is interfering with the pagination of the table

My table divides its items into 20 lines each and includes a search input above it to filter items based on written words. Each tool works fine independently - I can easily navigate through multiple pages when there are more than 20 items, and I can find s ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...