Evanss
Evanss

Reputation: 23593

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?

Upvotes: 0

Views: 80

Answers (5)

Prasanna
Prasanna

Reputation: 4636

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

Upvotes: 0

Ayush Gupta
Ayush Gupta

Reputation: 9295

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;
}, []);

Upvotes: 2

brk
brk

Reputation: 50291

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)

Upvotes: 0

Evanss
Evanss

Reputation: 23593

My ugly solution:

  let combineExercises = [];

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

  console.log(combineExercises);

Upvotes: 0

Sebastian Simon
Sebastian Simon

Reputation: 19485

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

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

Upvotes: 2

Related Questions