1

This is my Array in JavaScript, I want to merge teacher object below into combine single object to perform operations further.

const data = [
  {
    name: "ab",
    class: 1,
    grade: "A",
    teacher: {
      teacherName: "tab",
      age: 34,
      school: "ab pblc scl"
    }
  },
  {
    name: "cd",
    class: 2,
    grade: "B",
    teacher: {
      teacherName: "efg",
      age: 35,
      school: "cd pblc scl"
    }
  }
];

This is my Expected output. Here teacher object is combine with other single objects. Any idea how can I do this ?

const data = [
  {
    name: "ab",
    class: 3,
    grade: "B",
    teacherName: "kio",
    age: 38,
    school: "ab pblc scl"

  },
  {
    name: "de",
    class: 2,
    grade: "B",
    teacherName: "tde",
    age: 36,
    school: "de pblc scl"
   }

 }
];

Any help will be appreciated

0

2 Answers 2

3

You could destructure teacher and spread the rest of the array with teacher to a new object.

Methods:

  • destructuring assignment to teacher,

    result = data.map(({ teacher, ...object }) => ({ ...object, ...teacher }));
                       ^ ^^^^^^^            ^
    
  • rest in object destructuring for getting all other properties,

    result = data.map(({ teacher, ...object }) => ({ ...object, ...teacher }));
                       ^          ^^^^^^^^^ ^
    
  • spread syntax ... for getting copies of own enumerable properties of the object

    result = data.map(({ teacher, ...object }) => ({ ...object, ...teacher }));
                                                   ^ ^^^^^^^^^  ^^^^^^^^^^ ^
    

const
    data = [{ name: "ab", class: 1, grade: "A", teacher: { teacherName: "tab", age: 34, school: "ab pblc scl" } }, { name: "cd", class: 2, grade: "B", teacher: { teacherName: "efg", age: 35, school: "cd pblc scl" } }],
    result = data.map(({ teacher, ...object }) => ({ ...object, ...teacher }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

-1

You can use spread operator to do it.

const data = [
  {
    name: "ab",
    class: 1,
    grade: "A",
    teacher: {
      teacherName: "tab",
      age: 34,
      school: "ab pblc scl"
    }
  },
  {
    name: "cd",
    class: 2,
    grade: "B",
    teacher: {
      teacherName: "efg",
      age: 35,
      school: "cd pblc scl"
    }
  }
];

const newData = data.map(d => {
  const dClone = Object.assign({},d);
  delete dClone.teacher;
  return {
    ...dClone,
    ...d.teacher
  }
})

console.log(newData);

Comments

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.