Partho
Partho

Reputation: 2725

merge array object in another normal object

For example i have an array like

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

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

Now i want to merge those two object like

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

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

I am new to javascript, i am trying it many ways but couldn't. please help me to solve this using javascript.

Thanks...🙂 in advance.

Upvotes: 2

Views: 53

Answers (2)

Ryan Le
Ryan Le

Reputation: 8412

You can do it like so:

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

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

const student0 = [{ ...student[0], profile: [profile[0]] }];
const student1 = [{ ...student[1], profile: [profile[1]] }];

console.log(student0);
console.log(student1);

Upvotes: 1

Nitheesh
Nitheesh

Reputation: 20006

Use Array.map and array destructuring

const student = [ {firstName: 'Partho', Lastname: 'Das'}, {firstName: 'Bapon', Lastname: 'Sarkar'} ];
const profile = [ {education: 'SWE', profession: 'SWE'}, {education: 'LAW', profession: 'Law'} ];

const [student, student2] = student.map((node, index) => ({ ...node, profile: [profile[index]]}));
console.log(student, student2);

Upvotes: 2

Related Questions