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

initiate a page refresh upon selecting a particular checkbox

So I've got this code that saves around 30 checkbox selections to local storage, which is working fine. Then there's this separate checkbox below, when checked it automatically reloads the page: <input type="checkbox" id="autoload" class="aut ...

Designing access to data in JavaScript

As I work on developing my single page app, I find myself diving into the data access layer for the client-side. In this process, a question arises regarding the optimal design approach. While I am aware that JavaScript is callback-centric, I can't he ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...

Setting a CSS Variable with the Help of jQuery

I need help with changing the background color of a specific .div element when it is clicked on. I want the color to be a variable that can be changed by the user, and this change should occur when the document is ready. Currently, I am using a CSS variab ...

Implementing a function to save a file to a nested directory in node.js

Currently, I'm utilizing node and express with the following directory structure: public img css js server.js Within server.js, I have the code snippet below for writing to a png file: fs.writeFile('testfile.png', imageData, func ...

Tips on stopping the page from scrolling following an ajax request (return false not effective or potentially misplaced)

I am working on a project that involves displaying a tree with information from the Catalogue of Life, including details such as Kingdom, phylum, order, and more. My approach includes using ajax/php to interact with a mySQL database and javascript to handl ...

Can I trust the security of my credentials if they are able to be logged in the console

While working with NextJS, I've encountered a challenge in applying server-side rendering methods like getStaticProps to maintain credentials on the server rather than exposing them to the client. Despite my attempts, I couldn't find a straightfo ...

Expand the image to fill the entirety of the viewing area

Check out my development website. Whenever you click on an image, a photo slider (using photoswipe) pops up. Is there any way to have the image fill the entire viewport? I attempted using height: 100vh, width: auto, but it didn't work. ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

Transforming nested JSON files into nested jQuery divs

Is it possible to iterate through two JSON files that have a parent-child relationship based on simple ID primary and foreign keys? Can we then display the data in a list of divs with the following characteristics: Hierarchical - child divs should only a ...

Prevent draggable canvas elements from overlapping using jQuery

I'm currently working on a project where I need to make three canvas elements draggable while preventing them from overlapping each other. After researching similar issues, I came across the "jquery-ui-draggable-collision" library. Here is the code I ...

retrieve the value of a specific key using JSON stringify

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayo ...

Step by step guide on inserting a message (memo/sticky note) onto an HTML page

Wondering how to accomplish this: I've designed an HTML5 homepage and I'm looking to display a message to visitors, such as "Dear visitor, I am currently on vacation from....", in the form of a memo or sticky note positioned in the top right cor ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...

Uh-oh! Angular 6 has encountered an unexpected error with template parsing

I am currently working on an Angular application where I have integrated the FormsModule from '@angular/forms' in my app.module.ts. However, despite this, I keep encountering the error message No provider for ControlContainer. Error log: Uncaug ...

What is the best way to implement CSS rules for a hidden submenu?

Can anyone help me figure out how to apply CSS rules for a hidden submenu? I've attempted to use some JavaScript, but it's not working as expected. Below is a sample of the code I'm working with. The idea is that when you click on the anchor ...

Tips for implementing validation in JavaScript

I'm brand new to learning Javascript. Recently, I created a template for a login page and it's working perfectly fine. However, I am struggling with setting up validation and navigation. My goal is to redirect the user to another page if their us ...

Tips for Retrieving the Key Names of JSON Objects within a JSON Array

I'm trying to retrieve the object names "channelA" and "channelB". Here is the JSON data: [ { "channelA": { "programmes": [ { "start_utc": 1522208700, "stop_utc": 152220 ...

Use JavaScript to swap out various HTML content in order to translate the page

I am currently facing a challenge with my multilingual WordPress website that utilizes ACF-Field. Unfortunately, WPML is not able to translate the field at the moment (2nd-level-support is looking into it). As a solution, I have been considering using Java ...

At times, the Angular Modal Dropdown may unexpectedly open in an upward direction

Dealing with an AngularJS modal that contains a dropdown menu. The menu list is quite extensive. Most of the time, around 70%, the menu drops down in the lower direction which is fine. However, approximately 30% of the time, the dropdown menu appears in ...