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.

3
  • Does this answer your question? Add property to an array of objects Commented Sep 11, 2021 at 11:49
  • I am trying it using es6 destructuring but it creates another new object not merge them together Commented Sep 11, 2021 at 11:49
  • can you add your code? Commented Sep 11, 2021 at 11:52

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

thanks for answering this question , but can you solve this es6 destructuring way only, not using map

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.