从键/值对象中的值创建数组?

时间:2017-11-07 03:32:41

标签: javascript

我有一系列不同的练习:

exercises: {
  push: ['Push up', 'Bench press'],
  legs: ['Squat', 'Power squats'],
  pull: ['Pull up', 'Chin up'],
  cardioCore: ['Running high knees', 'Plank']
}

如何将所有这些组合成一个数组或对象?我需要创建这个:

allExercises: ['Push up', 'Bench press', 'Squat', 'Power squats', 'Pull up', 'Chin up', 'Running high knees', 'Plank']  

我也会按字母顺序排序,所以顺序并不重要。

我想我可以使用forEach执行此操作,如下所示:

let allExercises = [];
exercises.forEach(exerciseGroup=>{
  allExercises.push(exerciseGroup);
});

但这感觉有点乱。有更好的ES6解决方案吗?

5 个答案:

答案 0 :(得分:2)

是的,只需使用Object.valuesArray.prototype.reduce

const allExercises = Object.values(exercises)
  .reduce((array, subarray) => array.concat(subarray), []);

答案 1 :(得分:2)

这是另一种方式,ES6兼容。:

Object.getOwnPropertyNames(exercises)
.reduce((allExercises, exerciseName) => [...allExercises, ...(exercises[exerciseName])], [])

正如@stealththeninja所说,你也可以这样做以减少一大堆开销。

Object.getOwnPropertyNames(exercises).reduce((allExercises, exerciseName) => {
  allExercises.push(...exercises[exerciseName]);
  return allExercises;
}, []);

答案 2 :(得分:0)

[].concat.apply([], Object.values(exercises));

答案 3 :(得分:0)

我丑陋的解决方案:

  let combineExercises = [];

  Object.values(allExercises).forEach((exerciseGroup) => {
    exerciseGroup.forEach((exercise) => {
      combineExercises.push(exercise)
    })
  });

  console.log(combineExercises);

答案 4 :(得分:0)

您可以使用Object.values& spread operator



var exercises = {
    push: ['Push up', 'Bench press'],
    legs: ['Squat', 'Power squats'],
    pull: ['Pull up', 'Chin up'],
    cardioCore: ['Running high knees', 'Plank']
}
var allexercise ={},tempArray=[];
for(var keys in exercises){

    tempArray.push(...Object.values(exercises[keys]))
}
allexercise=tempArray;

console.log(allexercise)