简体   繁体   中英

Create an array from values in key/value object?

I have an array of different exercises:

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

How can I combine all of these into a single array or object? I need to create this:

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

I'm also going to sort alphabetically so the order isn't important.

I think I could do this with a forEach , something like this:

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

But this feels a bit messy. Is there a nicer ES6 solution?

Yes, just use Object.values and Array.prototype.reduce .

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

Here's another way, ES6 compatible.:

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

As @stealththeninja said, you can also do this to reduce a bunch of overhead.

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

My ugly solution:

  let combineExercises = [];

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

  console.log(combineExercises);

You can use 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM