如何将嵌套数组减少为单个对象数组

时间:2019-06-27 03:53:29

标签: javascript arrays object ecmascript-6

我正在尝试将嵌套数组简化为对象数组,因为我想将多级数组拆分为单个对象数组

这是我要减少的数组结构

var array1 = [
  {
    "course": "ABC"
    "skills":["skill1", "skill2"],
  },
  {
    "course": "DEF"
    "skills":["skill1"],
  },
  {
    "course": "GHI"
    "skills":["skill1", "skill2", "skill3"],
  }
]

我期望得到的结果

var array1 = [
  {
    "course": "ABC"
    "skill":"skill1",
  },
  {
    "course": "ABC"
    "skill":"skill2",
  },
  {
    "course": "DEF"
    "skill":"skill1",
  },
  {
    "course": "GHI"
    "skills":"skill1",
  },
  {
    "course": "GHI"
    "skills":"skill2",
  },
  {
    "course": "GHI"
    "skill": "skill3",
  }
]

5 个答案:

答案 0 :(得分:2)

var array1 = [
  {
    course: "ABC",
    skills:["skill1", "skill2"]
  },
  {
    course: "DEF",
    skills: ["skill1"]
  },
  {
    course: "GHI",
    skills: ["skill1", "skill2", "skill3"]
  }
];

const flatten = array =>
  array.reduce((results, item) => [...results, ...item.skills.map(skill => ({ course: item.course, skill: skill }))], []);


console.log(flatten(array1));

答案 1 :(得分:2)

您可以使用flatMap来执行此操作(如果在运行代码的地方受支持)。想法是映射每个课程,然后将每个技能进一步映射到您想要的对象,然后将其展平:

var array1 = [{
    "course": "ABC",
    "skills": ["skill1", "skill2"]
  },
  {
    "course": "DEF",
    "skills": ["skill1"]
  },
  {
    "course": "GHI",
    "skills": ["skill1", "skill2", "skill3"]
  }
];

var res = array1.flatMap(({course, skills}) => skills.map(skill => ({course, skill})));
console.log(res);

答案 2 :(得分:0)

您可以使用两个forEach来做到这一点。在第一个forEach循环中,外部数组和内部forEach迭代技能数组,并使用skills数组中的每个元素创建对象

var array1 = [{
    "course": "ABC",
    "skills": ["skill1", "skill2"],
  },
  {
    "course": "DEF",
    "skills": ["skill1"],
  },
  {
    "course": "GHI",
    "skills": ["skill1", "skill2", "skill3"],
  }
]


let newArr = [];
array1.forEach(function(item) {


  item.skills.forEach(function(elem) {
    newArr.push({
      course: item.course,
      skill: elem
    })
  })
});
console.log(newArr)

答案 3 :(得分:0)

您可以使用数组对象的map函数来执行此操作。 map遍历每个元素。

var array1 = [
  {
    "course": "ABC",
    "skills":["skill1", "skill2"],
  },
  {
    "course": "DEF",
    "skills":["skill1"],
  },
  {
    "course": "GHI",
    "skills":["skill1", "skill2", "skill3"],
  }
];

let mappedArray = [];

array1.map(el=>{
  el.skills.map(skill=>{
    mappedArray.push({
      course: el.course,
      skill: skill
    });
  });
});

console.log(mappedArray);

答案 4 :(得分:0)

大多数人想要的东西相反!在这里-使用reduce并进行传播的版本:

var array1 = [
  {
    "course": "ABC",
    "skills":["skill1", "skill2"],
  },
  {
    "course": "DEF",
    "skills":["skill1"],
  },
  {
    "course": "GHI",
    "skills":["skill1", "skill2", "skill3"],
  }
];

const res = array1.reduce((a, { skills, ...c }) => {
  skills.forEach(skill => a.push({ ...c, skills: skill }));
  return a;
}, []);

console.log(res);