2

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.

Partho
  • 2,153
  • 3
  • 17
  • 27
  • Does this answer your question? [Add property to an array of objects](https://stackoverflow.com/questions/38922998/add-property-to-an-array-of-objects) – GalAbra Sep 11 '21 at 11:49
  • I am trying it using es6 destructuring but it creates another new object not merge them together – Partho Sep 11 '21 at 11:49
  • can you add your code? – sid Sep 11 '21 at 11:52

2 Answers2

2

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);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
1

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);
Ryan Le
  • 7,708
  • 1
  • 13
  • 23
  • thanks for answering this question , but can you solve this es6 destructuring way only, not using map – Partho Sep 11 '21 at 11:54