How to return a new array of object from object nested props with reduce in JavaScript

I’m trying to return a new array of objects from the nested properties of another object. This is my current object:

const teams = {
  GRYFFINDOR: {
    display: 'Gryffindor',
    channel: ['#team-gryffindor'],
    ui: 'lion',
  },
  HUFFLEPLUFF: {
    display: 'Hufflepuff',
    channel: ['#team-hufflepuff'],
    ui: '', // empty string on purpose
  },
  SLYTHERIN: {
    display: 'Slytherin',
    channel: ['#team-slytherin'],
    ui: 'snake',
  },
}

Now, I’m trying to return an array of objects like so:

[
  { value: 'lion' },
  { value: '' },
  { value: 'snake' },
]

This is what I have tried:

const teamsUI = [Object.keys(teams).reduce((carry, item) => {
  return {...carry, ...{ ['value']: teams[item].ui  }}
}, {})];;

However, I get this:

console.log(teamsUI); // returns [ { value: 'snake' }]

What am I doing wrong?

Answer

You could do like this:

const teams = {
  GRYFFINDOR: {
    display: 'Gryffindor',
    channel: ['#team-gryffindor'],
    ui: 'lion',
  },
  HUFFLEPLUFF: {
    display: 'Hufflepuff',
    channel: ['#team-hufflepuff'],
    ui: '', // empty string on purpose
  },
  SLYTHERIN: {
    display: 'Slytherin',
    channel: ['#team-slytherin'],
    ui: 'snake',
  },
}

const result = Object.values(teams).map(({ ui }) => ({ value: ui }));

console.log(result);

Leave a Reply

Your email address will not be published. Required fields are marked *