Combine an array of objects into a regular object

Imagine having an array structure as shown below:

const student = [
  { firstName: 'Partho', Lastname: 'Das' },
  { firstName: 'Bapon', Lastname: 'Sarkar' }
];

const profile = [
  { education: 'SWE', profession: 'SWE' },
  { education: 'LAW', profession: 'Law' }
];

The objective is to combine these two objects, resulting in:

const student1 = [
  {
    firstName: 'Partho',
    Lastname: 'Das',
    profile: [{
      education: 'SWE',
      profession: 'SWE'
    }]
  }
];

const student2 = [
  {
    firstName: 'Bapon',
    Lastname: 'Sarkar',
    profile: [{
      education: 'LAW',
      profession: 'Law'
    }]
  }
];

Even though I'm new to JavaScript, I've attempted various approaches without success. Any guidance on resolving this using Javascript would be greatly appreciated.

Many thanks in advance!🙂

Answer â„–1

Implement Array.map with array destructuring technique

const team = [ {name: 'Mary', position: 'Manager'}, {name: 'John', position: 'Developer'} ];
const department = [ {deptName: 'IT', role: 'Manager'}, {deptName: 'HR', role: 'Recruiter'} ];

const [teamMember1, teamMember2] = team.map((person, idx) => ({ ...person, departmentInfo: [department[idx]]}));
console.log(teamMember1, teamMember2);

Answer â„–2

Here is one way to accomplish this:

const person = [
  { name: 'John', age: 30 },
  { name: 'Emily', age: 25 },
];

const job = [
  { title: 'Engineer', company: 'ABC Inc.' },
  { title: 'Teacher', company: 'XYZ School' },
];

const person0 = [{ ...person[0], job: [job[0]] }];
const person1 = [{ ...person[1], job: [job[1]] }];

console.log(person0);
console.log(person1);

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

Encountering a 500 error while trying to access a different file using the .get()

My current project involves setting up basic Express routing. However, every time I try to fetch data in order to link to a new page on my website, I encounter a 500 error. The main file managing the routing is Index.js. The content of Index.js: var expr ...

Incorporated asynchronous functionality, struggling to integrate it into the code

Previously, I used to utilize the following code for handling state: //get state MyClass.prototype.getState = function(key) { var value; switch(this._options.type){ case "cookie": value = $.cookie(key); ...

Locate and eliminate the item containing specific content

There are many <p> &nbsp </p> tags scattered throughout the description. I need to locate and delete any tags that contain only &nbsp. The description is enclosed in a container with the class name of desc_container. Below is an exampl ...

Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solu ...

How can I make the outer function in AJAX's onreadystatechange function return 'true'?

Within my Javascript/AJAX function below, I am striving for a return of true or false: function submitValidate() { var xmlhttp; xmlhttp = null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari try { xmlhttp ...

Ordering an Array of JavaScript Objects in a Custom Sequence (utilizing pre-existing methods)

Imagine we have an array of objects: ["c", "a", "b", "d"] Is there a way in ECMAScript or through a third-party JavaScript library to rearrange the objects in the first array to match the order specified by the second array, all within one line or functi ...

The Discord.js error message popped up, stating that it was unable to access the property 'then' since it was undefined

I'm currently working on implementing a mute command for my discord bot, but I'm encountering an error that says; TypeError: Cannot read property 'then' of undefined I am unsure of what is causing this issue and would greatly apprecia ...

Element remains hidden until the developer console is activated

On my website, I've noticed that certain LayerSlider elements are remaining invisible until: The window is resized I disable the Bookmarks bar in Chrome (quite strange, right?) I switch on the Chrome debugger tools This issue is not exclusive to Ch ...

Tips for transforming a date into a time ago representation

Can someone help me with converting a date field into a "timeago" format using jquery.timeago.js? $("time.timeago").timeago(); var userSpan = document.createElement("span"); userSpan.setAttribute("class", "text-muted"); userSpan.appendChild(document.crea ...

The Challenge of Iterating Through an Array of Objects in Angular Components using TypeScript

Could someone please explain why I am unable to iterate through this array? Initially, everything seems to be working fine in the ngOnInit. I have an array that is successfully displayed in the template. However, when checking in ngAfterViewInit, the conso ...

Obtain Outcome from a Nested Function in Node.js

I'm grappling with the concept of manipulating the stack in JS and hoping this exercise will provide some clarity. Currently, I'm attempting to create a function that makes a SOAP XML call, parses the data, and returns it when called. While I c ...

Enhancing Kendo Grid with Checkbox Columns

I am facing a situation with my kendo grid where I need to insert two checkbox columns in addition to the existing set of columns. <script id="sectionPage" type="text/kendo-tmpl"> @(Html.Kendo().Grid<SectionPageModel>() .Na ...

Leveraging Masonry.js with dynamically created divs using jQuery

Recently, I discovered Masonry.js and was excited to incorporate it into my projects. To test my skills, I decided to create a page that would display 16 divs with random heights and colors every time I clicked a button. However, I'm encountering an i ...

I have incorporated jquery-1.2.6.js into my project but I am encountering difficulties utilizing the live method

C# foreach (DataRow Row in oDs.Tables[0].Rows) { LitPreferances.Text += "<Li ID=LI_" + Row["pk_Preference_Branch_ID"].ToString() +"_"+ Row["pk_Preference_BranchType_ID"].ToString() +">" + Row["Branch_Name"].ToString() + "&nbsp;&nbsp;< ...

Error encountered on NodeJS server

Today marks my third day of delving into the world of Angular. I've come across a section that covers making ajax calls, but I've hit a roadblock where a tutorial instructed me to run server.js. I have successfully installed both nodejs and expre ...

What causes the mounted hook in Vue to be triggered multiple times when used within a plugin or mixin?

How can I prevent repetitive behavior in my code? Is this a bug that needs fixing? Take a look at the plugin below: const globala = { install(Vue) { Vue.mixin({ mounted() { console.log('hi') } }) } } And here&apos ...

Utilize the power of REACT JS to transform a specific segment within a paragraph into a hyperlink. Take advantage of the click event on that hyperlink to execute an API request prior to

In React JSX, I'm encountering an issue trying to dynamically convert a section of text into an anchor tag. Additionally, upon clicking the anchor tag, I need to make an API call before redirecting it to the requested page. Despite my attempts, I have ...

I am looking for a tool that can extract XML data from a remote URL and convert it into JSON format for easy retrieval using JavaScript

Grabbing XML directly from your own domain's local URL is simple, but doing so cross-domain can be more challenging. How can you retrieve the XML data located at using javascript? ...

Using regular expressions to extract the value of a specific key from a JavaScript object

After scraping a webpage with BeautifulSoup and requests, I came across this snippet of code within the HTML content: $create(Web.Scheduler, { "model": '{"apt":[0]}', "timeZone": "UTC", "_uniqueI ...

Ensure child elements do not surpass parent size in HTML/CSS/Javascript without altering the children directly

I am intrigued by how iframes neatly encapsulate all site data within a frame and adjust it to fit the size. Is there any method to achieve this functionality in an HTML wrapper? Can the wrapper be configured so that regardless of the content, it is dis ...