Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information:

[
  {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"},
  {"Project":"Project 2","Domain":"Domain2","Manager":"Manager2"},  
  {"Project":"Project 3","Domain":"Domain3","Manager":"Manager1"},
  {"Project":"Project 4","Domain":"Domain1","Manager":"Manager3"},
  {"Project":"Project 5","Domain":"Domain5","Manager":"Manager4"},
  {"Project":"Project 6","Domain":"Domain6","Manager":"Manager5"},
  {"Project":"Project 7","Domain":"Domain5","Manager":"Manager2"},
  {"Project":"Project 8","Domain":"Domain2","Manager":"Manager5"},
  {"Project":"Project 9","Domain":"Domain7","Manager":"Manager8"},
  {"Project":"Project 10","Domain":"Domain9","Manager":"Manager9"},
  {"Project":"Project 11","Domain":"Domain6","Manager":"Manager1"}
]

I need to extract all distinct domains and managers into separate string arrays.

Here is my approach:

let Domains:string[]=[];
Domains= res.map((x)=>x.Domain);
let Managers:string[]=[];
Managers= res.map((x)=>x.Manager);

The current implementation works, but there are duplicate values in both arrays.

Is there a better way to assign these variables using a single map function instead of assigning them separately?

Answer №1

An effective strategy is to utilize object keys as a unique set. A simple yet effective approach to implement this is:

Domains = Object.keys(res.reduce((acc, val) => { acc[val.Domain] = val.Domain; return acc; }, {}));

In the above code snippet, each "domain" value is added as a key in an object, resulting in a list of key names at the end.

The recommended practice is to leverage Set: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Answer №2

const data = [{"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"},{"Project":"Project 2","Domain":"Domain2","Manager":"Manager2"},{"Project":"Project 3","Domain":"Domain3","Manager":"Manager1"},{"Project":"Project 4","Domain":"Domain1","Manager":"Manager3"},{"Project":"Project 5","Domain":"Domain5","Manager":"Manager4"},{"Project":"Project 6","Domain":"Domain6","Manager":"Manager5"},{"Project":"Project 7","Domain":"Domain5","Manager":"Manager2"},{"Project":"Project 8","Domain":"Domain2","Manager":"Manager5"},{"Project":"Project 9","Domain":"Domain7","Manager":"Manager8"},{"Project":"Project 10","Domain":"Domain9","Manager":"Manager9"},{"Project":"Project 11","Domain":"Domain6","Manager":"Manager1"}]

// Using Set for unique values
/*const result = data.reduce((accumulator, item) => {
  Object.keys(item).forEach(key => accumulator[key] = accumulator[key] ? [...new Set([...accumulator[key], item[key]])] : [item[key]]);
  return accumulator;
}, {});*/

// without Set
const result = data.reduce((accumulator, item) => (Object.keys(item).forEach(key => !accumulator[key] ? accumulator[key] = [item[key]] : !accumulator[key].includes(item[key]) ? accumulator[key].push(item[key]) : '') , accumulator), {});

// to access
console.log(result['Project']);
console.log(result['Manager']);
console.log(result['Domain']);
.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 more efficient method to tally specific elements in a sparse array?

Review the TypeScript code snippet below: const myArray: Array<string> = new Array(); myArray[5] = 'hello'; myArray[7] = 'world'; const len = myArray.length; let totalLen = 0; myArray.forEach( arr => totalLen++); console.log(& ...

Transforming ActivatedRoute.queryParams into a Promise

Instead of subscribing to route.queryParams as an Observable, I want it to be a Promise so that I can use async/await for function calls in ngOnInit. However, my attempt at this is not working as expected. The code below does not produce any output: constr ...

Protected Node.js API paths

Recently, I was developing a login with OTP feature for my app. The front-end is being built using Angular and the back-end on ExpressJs. However, I have been struggling to find a way to secure the API. Every time I test the API using Postman, it works per ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

The BooleanField component in V4 no longer supports the use of Mui Icons

In my React-Admin v3 project, I had a functional component that looked like this: import ClearIcon from '@mui/icons-material/Clear' import DoneIcon from '@mui/icons-material/Done' import get from 'lodash/get' import { BooleanF ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

NextJS: Build error - TypeScript package not detected

I'm facing an issue while setting up my NextJS application in TypeScript on my hosting server. On my local machine, everything works fine when I run next build. However, on the server, I'm encountering this error: > next build It seems that T ...

Angular application hosted on Apache2 with SSL configured to communicate with a Spring Boot API running on port 8080

After developing a small application using Angular and an API with Spring Boot that includes an embedded Tomcat server, I decided to deploy them on a Raspberry Pi while configuring an SSL certificate with Let's Encrypt. The deployment process involve ...

A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data: "Id":10001, "name":"John" "Id":10002, ...

What could be causing the issue of my application not being able to operate on the specified port on Heroku?

After spending two whole days trying to decipher the Heroku error message with no success, I'm still unable to pinpoint what is causing the issue. 2021-07-18T04:27:08.741998+00:00 app[web.1]: {"level":30,"time":1626582428741,&quo ...

What is the process for installing npm dependencies to a specific directory without creating a node_modules folder?

I recently published a package called main-package, which has a dependency on another package called sub-package that is already available on npm. However, when I install main-package, it creates a node_modules folder with both packages at the same level. ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

Update the HttpClient URL in Angular based on language switch

I am currently working on creating a portfolio where the language changes in the menu will dynamically update the components to load the appropriate JSON data. I attempted to use BehaviourSubject and subject, but I found them difficult to understand and im ...

Block-level declarations are commonly used in TypeScript and Asp.net MVC 5

In my asp.net mvc5 project, I decided to incorporate TypeScript. I created an app.ts file and installed the nuget-package jquery.TypeScript.DefinitelyTyped. Here is a snippet of the app.ts code: /// <reference path="typings/jquery/jquery.d.ts"/> cl ...

Can the type of a prop be specified in the parent component before it is passed down to the children components that utilize the same prop?

In my codebase, I have a component called NotFoundGuard. This component only renders its children if a certain condition is true. Otherwise, it displays a generic fallback component to prevent redundancy in our code. I am trying to figure out if there is ...

Is it possible to implement typed metaprogramming in TypeScript?

I am in the process of developing a function that takes multiple keys and values as input and should return an object with those keys and their corresponding values. The value types should match the ones provided when calling the function. Currently, the ...

OAuth does not support this response type

Hi there, I'm currently working on a web application using Angular 2. The back end has oauth authentication through webapi. In the front end, I am utilizing Angular 2. When attempting to log in, I execute the following code: private login() { ...

Exploring Jasmine and Karma for testing Angular 5 HTTP requests and responses

I am brand new to the concept of Test-Driven Development (TDD) and I am currently in the process of debugging a complex Angular 5 application for the company I work for. The application is functioning without any issues, but now I need to incorporate test ...

When an empty array is returned from a catch statement in an async/await method, TypeScript infers it as never

Function getData() returns a Promise<Output[]>. When used without a catch statement, the inferred data type is Output[]. However, adding a catch statement in front of the getData() method changes the inferred data type to Output[] | void. This sugge ...