combine the value of one key with the value of another key within an array

const array = [{
    id: 1,
    name: 'Bob',
    education: [{
      degree: 'bachelors',
      Major: 'computers'
    }, {
      degree: 'masters',
      Major: 'computers'
    }]
  },
  {
    id: 2,
    name: 'Alice',
    education: [{
      degree: 'bachelors',
      Major: 'electronics'
    }, {
      degree: 'masters',
      Major: 'electronics'
    }]
  }
];


const resultArray = [{
    id: 1,
    name: 'Bob',
    education: [{
      degree: 'bachelors',
      Major: 'computers',
      id: 1
    }, {
      degree: 'masters',
      Major: 'computers',
      id: 1
    }]
  },
  {
    id: 2,
    name: 'Alice',
    education: [{
      degree: 'bachelors',
      Major: 'electronics',
      id: 2
    }, {
      degree: 'masters',
      Major: 'electronics',
      id: 2
    }]
  }
];

I need assistance in adding the id with its corresponding value from the array to each object in the education array. Any suggestions on how I can achieve this?

Your help would be greatly appreciated.

Answer №1

To extract each object within an array and assign the 'id' value to the 'education' array, you can iterate over the array and use a loop to achieve this. Either a simple 'for' loop or Array.forEach() method can be employed for this purpose. Any changes made to an object property will directly modify the original object.

IMPLEMENTING forEach()

const array = [{
  id: 1,
  name: 'Bob',
  education: [{
    degree: 'bachelors',
    Major: 'computers'
  }, {
    degree: 'masters',
    Major: 'computers'
  }]
}, {
  id: 2,
  name: 'Alice',
  education: [{
    degree: 'bachelors',
    Major: 'electronics'
  }, {
    degree: 'masters',
    Major: 'electronics'
  }]
}];
array.forEach((item) => {
  item.education.forEach((educationObj) => {
    educationObj['id'] = item.id;
  });
});
console.log(array);

USING for

const array = [{
  id: 1,
  name: 'Bob',
  education: [{
    degree: 'bachelors',
    Major: 'computers'
  }, {
    degree: 'masters',
    Major: 'computers'
  }]
}, {
  id: 2,
  name: 'Alice',
  education: [{
    degree: 'bachelors',
    Major: 'electronics'
  }, {
    degree: 'masters',
    Major: 'electronics'
  }]
}];
for(var i=0; i<array.length; i++){
 for(var j=0; j<array[i].education.length; j++){
    array[i].education[j]['id'] = array[i].id;
  }
}
console.log(array);

Answer №2

To accomplish this task, you simply need to use a nested .map() method like so:

const resultArray = array.map(x => {
  x.education = x.education.map(e => {
    e.id = x.id;
    return e;
  });
  return x
});

The first .map() function is used to iterate over and transform your original array, while the inner .map() is utilized to modify and transform the inner education array.

Here is a demonstration:

const array = 
      [{ id: 1, name: 'Bob', education: [{degree: 'bachelors', Major: 'computers'}, {degree: 'masters', Major: 'computers'}] },
       { id: 2, name: 'Alice', education: [{degree: 'bachelors', Major: 'electronics'}, {degree: 'masters', Major: 'electronics'}] }];

const resultArray = array.map(x => {
  x.education = x.education.map(e => {
    e.id = x.id;
    return e;
  });
  return x
});

console.log(resultArray);

Answer №3

One effective approach is to utilize nested maps for resolving the issue.

const updatedArray = array.map((arr) => {
  array.education = arr.education.map((e) => {
   e.id = arr.id;
   return e;
 });
 return arr;
});

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

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

Enhance your table with custom styling by incorporating the seanmacisaac table and placing the tbody within a div

I am looking to make adjustments to a Jquery sortable, searchable table created by seanmacisaac. For more information, visit the link: Does anyone know how to set the height of the tbody to a fixed value while allowing vertical scrolling (overflow-y)? & ...

To achieve two-way binding with a scope variable, it is necessary to enclose it within an

I am in need of creating a basic search feature for some items. I have designed a simple control with a button that clears the search query: <div class="item item-input item-button-right"> <i class="icon ion-ios-search placeholder-icon">&l ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

warning: issue detected with the password value in jquery

Why is the following script generating an incorrect JavaScript alert message? <script type="text/javascript> $('#cpassword').change(function() { var pass=$('#password').val(); alert(pass); var cpass=$(& ...

JavaScript Library function in Angular Component throwing Type Error: Function is Not Recognized

I created a custom Javascript library to group together essential functions that many Angular Components require. The library called calcs.js includes functions like this: function calculateCosts(object) { do some stuff..... return answer; } To use t ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Is it possible for me to automatically send the user's email and username through code without requiring any information from them while using the tawk.to chat widget?

I need assistance with automatically sending the user's email and name when they open a chat window. I have tried various methods to pre-fill the form data but it still appears empty. Please let me know if there is something I am missing. Thank you ta ...

Deleting a sentence from a text document

Is there a way to remove a row from a text file without leaving empty lines? See the Example and Example2. Consider this scenario: Hello Hello2 String After deletion, the file should look like this: Hello Hello2 I attempted the following code but it re ...

Attempting to decode the string prior to selecting an item from the Vue.js/Nuxt array

Hey there, I really appreciate anyone who can assist me with this. I've been dabbling in Laravel for a few months and now I'm trying to dive into studying Nuxt. The specific type of translation I need help with is proving to be quite challenging ...

What is the concept of nested includes in sequelize?

Is it possible to perform a nested include in Sequelize? I have a table called products that has a one-to-many relationship with comments, and the comments table has a many-to-one relationship with the users table. Each comment has a user_id and product_id ...

Customizing buttons on Dialogs in JavaScript to have dynamic names

There is something on my website that resembles this: $("#id").html(msg2show).dialog({ //Other attributes buttons: { "Yes": function() {//Code}, "No": function() {//Code} } ...

What is the syntax for utilizing cookies within the `getServerSideProps` function in Next.js?

I am struggling to pass the current language to an endpoint. Despite attempting to retrieve the language from a Cookie, I keep getting undefined within the getServerSideProps function. export async function getServerSideProps(context) { const lang = aw ...

What is the best way to update a canvas chart when the side menu is hidden?

I am facing an issue with the layout of my webpage, which includes a left side menu and a canvas chart. The left side menu occupies the first 155 pixels of the width, leaving the rest for the canvas chart set to a width of 100%. However, when I close the ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

Steps for embedding a custom function in a switch statement

I am attempting to run a switch statement based on the argument provided to the function below. I have been trying to call different functions depending on the argument passed. However, I encountered an Uncaught ReferenceError in the beginning of the .js f ...

Draggable vue includes a Textarea HTML element that allows users to easily

The issue lies in implementing the draggable functionality on a textarea element. While the textarea allows text input and deletion, trying to select the text using pointer events triggers the dragging function instead, as shown in the image below: https ...

Leveraging Object.assign for updating fields in Firebase documents

Currently, I am working on a website that allows users to create new projects by filling out a form with all the necessary project information. Within this form, there is a file input field where users can upload images and documents. I have successfully i ...