Generate a collection of elements using a different collection as a reference

I am struggling with an array of objects:

let data = [{
    createdDate: "2222",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c3d487c6d7b7c266b6765">[email protected]</a>",
    histories: [],
    meta: {
      profilePic: "test"
    },
    name: {
      first: "Vikash",
      last: "Grv"
    },
    role: {
      id: "123",
      name: "test role 2"
    },
    specialities: [],
    status: "active",
    __v: 0,
    _id: "123"
  },
  {
    createdDate: "2222",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3d7c6d0d796e3d7c6d0d78dc0ccce">[email protected]</a>",
    histories: [],
    meta: {
      profilePic: "test"
    },
    name: {
      first: "Vikash",
      last: "Grv"
    },
    role: {
      id: "123",
      name: "test role 2"
    },
    specialities: [],
    status: "active",
    __v: 0,
    _id: "123"
  },
  {
    createdDate: "2222",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e6f7e1e6a7d2e6f7e1e6bcf1fdff">[email protected]</a>",
    histories: [],
    meta: {
      profilePic: "test"
    },
    name: {
      first: "Vikash",
      last: "Grv"
    },
    role: {
      id: "123",
      name: "test role 2"
    },
    specialities: [],
    status: "active",
    __v: 0,
    _id: "123"
  },
]

Now, I aim to form another array of objects as follows:

const newData = [{
    teamMember: 'Vikas Grv',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86f2e3f5f2b3c6f2e3f5f2a8e5e9eb">[email protected]</a>',
    role: 'test role 2',
    assignedOn: null
  }, {
    teamMember: 'Vikas Grv',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e195849295d4a195849295cf828e8c">[email protected]</a>',
    role: 'test role 2',
    assignedOn: null
  },
  {
    teamMember: 'Vikas Grv',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c6d7c1c687f2c6d7c1c69cd1dddf">[email protected]</a>',
    role: 'test role 2',
    assignedOn: null
  }
]

The values in the team member field are a combination of the first and last names, emails stay the same, roles come from the key value 'name' under role, and assignedOn is set to null.

Any suggestions on how to achieve this transformation?

Answer №1

If you want to utilize the `map` function:

var data = [{createdDate: "2222",email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15617066612055617066613b767a78">[email protected]</a>",histories: [],meta: {profilePic: "test"},name: {first: "Vikash", last: "Grv"},role: {id: "123", name: "test role 2"},specialities: [],status: "active",__v: 0,_id: "123"}, {createdDate: "2222",email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="21554452551461554452550f424e4c">[email protected]</a>",histories: [],meta: {profilePic: "test"},name: {first: "Vikash", last: "Grv"},role: {id: "123", name: "test role 2"},specialities: [],status: "active",__v: 0,_id: "123"},{createdDate: "2222",email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="30445543440570445543441e535f5d">[email protected]</a>",histories: [],meta: {profilePic: "test"},name: {first: "Vikash", last: "Grv"},role: {id: "123", name: "test role 2"},specialities: [],status: "active",__v: 0,_id: "123"},];

var result = data.map(({name, role, email})=>({teamMember:Object.values(name).join(" "), email,role:role?.name, assignOn:null}));

console.log(result);

Answer №2

Here is an example of how to achieve this:

import { Component } from '@angular/core';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data = [
    {
      createdDate: "2222",
      email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83f7e6f0f7b6c3f7e6f0f7ade0ecee">[email protected]</a>",
      histories: [],
      meta: { profilePic: "test" },
      name: { first: "Vikash", last: "Grv" },
      role: { id: "123", name: "test role 2" },
      specialities: [],
      status: "active",
      __v: 0,
      _id: "123"
    },
    {
      createdDate: "3333",
      email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cf8e9fff8bfccf8e9fff8a2efe3e1">[email protected]</a>",
      histories: [],
      meta: { profilePic: "test" },
      name: { first: "jhon", last: "doe" },
      role: { id: "123", name: "test role 3" },
      specialities: [],
      status: "active",
      __v: 0,
      _id: "1234"
    },
    {
      createdDate: "4444",
      email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483c2d3b3c7d083c2d3b3c662b2725">[email protected]</a>",
      histories: [],
      meta: { profilePic: "test" },
      name: { first: "nathy", last: "gyr" },
      role: { id: "123", name: "test role 4" },
      specialities: [],
      status: "active",
      __v: 0,
      _id: "1234"
    },
  ]

  constructor() {

    let result = this.data.map((item) => {
      return {
        teamMember: item?.name?.first + item?.name?.last,
        email: item?.email,
        role: item?.role?.name,
        assignedOn: null
      }
    }

    );
    console.log(result)
  }

}

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

Change a JavaScript object into an array with different options while still maintaining the keys

I am attempting to transform the following JavaScript object: image_uploads: [ 0: { upload_id: 50, }, 1: { upload_id: 51, }, 2: { upload_id: 52, }, ] Into separate entries using this structure for inclusion in the body of a POST r ...

Creating a 2D array from a 1D array of character strings in C is a straightforward process that involves defining

After successfully creating a similar function where strings were integers, I encountered an issue when attempting to change the data type from int to char. int main() { char A[ ] = "RRTTYYHH"; int len = 8; char B[2][4]; int i; int j; int k = 0; ...

Ways to insert a div element into the HTML display utilizing JavaScript

There's a method I'd like to use to dynamically add a div to the view using JavaScript. I attempted hiding the div on page load and then showing it through JavaScript. However, what ends up happening is that the div content appears briefly on l ...

How can I implement a dynamic progress bar using Ionic 4?

I am currently working on developing a progress bar that increases by 1% every time the user clicks a button. This is what my HTML code looks like: <ion-button *ngFor="let progress of progress" (click)="add(progress)">Progress</ion-button> &l ...

h1 tag set for jQuery AJAX activation

Currently working on a website that heavily relies on ajax. Encountering an issue that hasn't been solved through online resources. Now, I'm sharing my function for fetching a page: function loadTemplate(name, replaceWholePage = true){ $.wh ...

javascript change string into an array of objects

let dataString = "{lat: -31.563910, lng: 147.154312};{lat: -33.718234, lng: 150.363181};{lat: -33.727111, lng: 150.371124}"; let dataArray = dataString.split(';'); Produces the following output: let dataArray = [ "{lat: -31.563910, lng: 147 ...

The computation outcome is not being displayed within the <h2> tag. Issue may be related to either

I am currently working on a percentage calculator. The calculation is functioning properly but the result is only being displayed in the input. I would like the result to also be shown in the h2. Is there a way to achieve this? $(document).on("change ke ...

Utilizing the fetch() method to transmit GET data within the body rather than directly embedding it in the URL

I am in the process of converting this jQuery call to vanilla JavaScript using fetch() following the guidance provided by MDN (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options). $.ajax( { ...

Access the value of a JSON property, return null if the key is not found, all in one line of JavaScript code

How about a fun analogy in Python: fruits_dict = {"banana": 4, "apple": 3} num_apples = fruits_dict.get("apple", None) num_oranges = fruits_dict.get("orange", None) print(num_apples, num_oranges) The result would be: 3 None If we switch gears to Jav ...

Updating an element in an array using PHP

In PHP, imagine I have an array like this: Array ( [0] => Array ( [name] => Test [year] => 2015 ) ) These values are retrieved from a MySQL database. Now, I am looking for an easy solution to update t ...

Troubleshooting a Simple JavaScript Game: Mastermind Edition

Currently, I am working on a JavaScript version of the well-known board game "Mastermind". I have been facing some fundamental issues, mainly with JavaScript arrays and how to reference their values or elements. Despite spending quite a bit of time trying ...

Changing values in object using Mongoose in MongoDB

Currently, I have a basic collection stored in MongoDB using Mongoose. My users model consists of a single field of type object, and I am looking to dynamically modify this object. However, despite my attempts using findByIdAndUpdate(), findById, findOne( ...

Issue with dropdown element not triggering JavaScript onchange event

I am in the process of developing an application that involves searching a database and enabling users to compare the results. To achieve this, I require multiple dependent drop-down menus. While I have some understanding of HTML and PHP, my coding experti ...

Angular's change detection mechanism triggers too frequently

I'm dealing with a situation in one of my controllers where I have the following code: @HostListener('window:resize') onResize() { this.currentWindowWidth = window.innerWidth; } This code determines different views to render based on the ...

Can the validity of a Control's property be adjusted?

Is it possible to establish the valid property of a control titled "titleCtrl"? I attempted .dart titleCtrl.valid = false; Unfortunately, this results in an error. However, retrieving the valid state poses no issue. ...

Sort through object attributes according to a different object

I have two sets of data represented by objects object_a and object_b. I want to extract the items from object_a that correspond to the IDs found in object_b. const object_a = { 100: "Stack Overflow", 101: "MDN Web Docks", 10 ...

Trying to use the `await` keyword results in a "SyntaxError: Unexpted identifier" message, even when used within an `async` function

Encountering an error with Javascript's await when using it inside an async module let ImagesArray = await getImages(); ^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThis ...

Tips for aligning an element in the center in relation to its sibling above

Help Needed with Centering Form Button https://i.sstatic.net/QhWqi.png I am struggling to center the "Send" button below the textarea in the form shown in the image. Despite trying various methods like using position absolute, relative, and custom margin ...

Introduce a specialized hierarchical data structure known as a nested Record type, which progressively ref

In my system, the permissions are defined as an array of strings: const stringVals = [ 'create:user', 'update:user', 'delete:user', 'create:document', 'update:document', 'delete:document&ap ...

The duplicate code is failing to display any output

Welcome to my first question here! Please excuse any rookie mistakes. I am currently working on a specialized calculator using HTML, JS (with jQuery), and CSS. This calculator is designed to handle multiple inputs and perform various calculations on a sing ...