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

Example of a floating undo bar using a dynamic function in a Vuex store module

Issue Overview Trigger the mutation or action of Vuex store module A to execute an external function. This external function can belong to another Vuex store module (e.g. B). A should store a reference to the external method (e.g. mutation or action from ...

Integrate a service component into another service component by utilizing module exports

After diving into the nestjs docs and exploring hierarchical injection, I found myself struggling to properly implement it within my project. Currently, I have two crucial modules at play. AuthModule is responsible for importing the UserModule, which conta ...

Code update results in a blank screen on Angular-NativeScript application

Currently diving into the world of NativeScript, I encountered a curious issue. Installing one of the sample apps was a breeze, with the emulators functioning perfectly post-installation. However, as soon as I make even the slightest code tweaks and save t ...

Is there a way to position the input directly above the div in the center?

In my HTML code, I have a div container with an input and another nested div element that contains various other elements. My goal is to center the input element in relation to the parent div, where error messages are displayed. Currently, both elements s ...

How to showcase information stored in Firebase Realtime Database within an Ionic application

Looking to list all children of "Requests" from my firebase realtime database in a structured format. Here's a snapshot of how the database is organized: https://i.stack.imgur.com/5fKQP.png I have successfully fetched the data from Firebase as JSON: ...

The CSS root variable is failing to have an impact on the HTML element's value

I'm in the process of changing the text color on home.html. I've defined the color property in a :root variable, but for some reason, it's not appearing correctly on the HTML page. Take a look at my code: home.scss :root { --prim-headclr : ...

Display the toggle button for expanding/collapsing text only when the length of the string exceeds 50 characters

Is there a way to only show a "read more/less" button in a table if the content exceeds 50 characters? The table contains a mix of content, some short announcements with about 10 characters and others with over 100. <div class="col"> <span ng-c ...

Why do I keep being told that the property doesn't exist?

I have the following code in one file: function test<T extends {}>(arg:T):any { return arg.name } In another file, I have this code: interface IItem { name: string } console.log(test<IItem>({name:'3'})) When I try to access ...

Angular Throws 'Expression Changed After Check' Error When Behavior Subject is Triggered

In my Angular 11 project, I am utilizing a BehaviorSubject to update the toolbar content from various components. The toolbar subscribes to the BehaviorSubject in the following manner: <breadcrumbs [crumbs]="messageService.getBreadcrumbs() | async& ...

Exploring ways to fetch an HTTP response using a TypeScript POST request

I have been looking at various questions, but unfortunately, none of them have provided the help I need. The typescript method I am currently working with is as follows: transferAmount(transfer: Transfer): Observable<number> { return this.http .po ...

Angular 12 route loading component without needing to explicitly declare it in the module registration

Update on Angular Version and CLI Attention: We have a significant change coming up with the next release regarding the CLI npm package. The package will be moved to "@angular/cli" and will only support Node version 6.9 and above. After this transition, t ...

Parsing error encountered while trying to handle an unexpected token at line 214, character 33. It appears that an appropriate loader is missing to process this particular file type

I've been developing a Typescript React project for the past few months without any issues. However, things took a turn yesterday when I decided to run npm audit fix and npm audit fix --force in order to address some security concerns that appeared ou ...

Angular WebSocket refusing connection attempts

After successfully setting up a WebSocket server in go, I encountered an issue when trying to connect to the server in Angular. The connection works flawlessly when tested using Postman with the URL ws://localhost:3000/ws. However, replicating the same pro ...

Can you provide guidance on effectively utilizing a Pinia store with Vue3, Pinia, and Typescript?

I'm currently facing challenges while using the Pinia store with TypeScript and implementing the store within a basic app.vue Vuejs3 option api. Here is my app.js file: import {createApp} from 'vue' import {createPinia} from "pinia&quo ...

What is the best way to access an optional field in Typescript without causing errors?

Is there a way to dereference an optional field from an interface in the following scenario? interface Sample { key1?: Array<Obj1> } interface Obj1 { a?: Obj2; } interface Obj2 { b?: string; } const a: Sample["key1"][number][" ...

Tips for troubleshooting an Angular app with just a single click using WebStorm!

After conducting some research, I have checked the following resources: How to debug an application in Angular2 using angular-cli? https://manuel-rauber.com/2016/09/30/how-to-debug-angular-2-with-webstorm/ The troubleshooting method mentioned on the Je ...

Exploration of narrowing union types in React with TypeScript

import { Chip } from "@mui/material"; type CourseFilterChipsRangeType = { labels: { from: string; to: string }; values: { from: number; to: number }; toggler: (from: number, to: number) => void; }; type CourseFilterChipsCheckType = { ...

An error arises in Typescript when the reducer state does not update upon clicking. The error message indicates that the properties 'state' and 'dispatch' are not recognized on the type 'UserContextType | null'

Having recently delved into typescript with react, I've encountered some issues. Despite trying various solutions, the state doesn't seem to work properly and I keep getting a typescript error stating: Property 'state and dispatch' does ...

Obtaining the count of a specific column in Angular 6 by grouping objects based on the same value in an array

In TypeScript, I have an array of objects and I am using a foreach loop. The array contains 2 columns with a progress value of 100, while the rest have values less than 100. My goal is to calculate the count of columns with a progress value of 100, which ...

Changing data types conditionally in Angular using TypeScript

My angular component relies on the API Response for its functionality. I receive these responses from an external API. When there are no errors Data : { Status: string; Data: number; } When an error occurs, this is what I get. Data : { Status: string; ...