将具有相同键的嵌套对象合并到JavaScript中的单个对象中

时间:2019-07-10 12:40:43

标签: javascript arrays object

这是我在JavaScript中使用的数组,我想将下面的教师对象合并为合并单个对象以进一步执行操作。

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 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"
   }

 }
];

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

您可以解构teacher并使用teacher将数组的其余部分扩展到新对象。

方法:

  • destructuring assignmentteacher

    result = data.map(({ teacher, ...object }) => ({ ...object, ...teacher }));
                       ^ ^^^^^^^            ^
    
  • rest in object destructuring获取所有其他属性,

    result = data.map(({ teacher, ...object }) => ({ ...object, ...teacher }));
                       ^          ^^^^^^^^^ ^
    
  • spread syntax ...用于获取对象自身的可枚举属性的副本

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

答案 1 :(得分:-1)

您可以使用传播运算符来做到这一点。

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