简体   繁体   中英

How would you change values/add to nested object data inside array of objects using Javascript?

const beers = [
  {
    id: '100',
    name: 'stoneys'
  },
  {
    id: '200',
    name: 'budweiser'
  },

  {
    id: '300',
    name: 'miller'
  },

  {
    id: '400',
    name: 'corona'
  }
];

const people = [
  {
    name: 'steve',
    teams: [
      {
        name: 'pirates',
        beers: ['100']
      },
      {
        name: 'penguins',
        beers: ['300']
      }
    ]
  },
  {
    name: 'jim',
    teams: [
      {
        name: 'indians',
        beers: ['200']
      },
      {
        name: 'blue jackets',
        beers: ['100', '400']
      }
    ]
  }
];

let newPeople = people.map(fan => {
  fan.teams.map(team => {
    team.beers.map(beer => beers.filter(brand => brand.id === beer)[0])
  });
});

Above is a sample I put together to best demonstrate my question. I am having trouble understanding why nested mapping (.map()) of object arrays is not allowing me to alter the nested data. When I console log results, I am either getting an "[undefined, undefined]' or the unchanged "people" array.

I would like to return the same array as "people" except replace the nested "beers" array (people.teams.beers[]) with corresponding objects from the "beers" array. Example of a successful result below:

 {
    name: 'steve',
    teams: [
      {
        name: 'pirates',
        beers: [
          {
            id: '100',
            name: 'stoneys'
          }
        ]
      },
      {
        name: 'penguins',
        beers: [
          {
            id: '300',
            name: 'miller'
          }
        ]
      }
    ]
  }

Array.map expects a function which takes single array element as parameter and returns a mapped value. In your case you're not returning any value from mapping functions therefore you're getting undefined twice

 const beers = [ { id: '100', name: 'stoneys' }, { id: '200', name: 'budweiser' }, { id: '300', name: 'miller' }, { id: '400', name: 'corona' } ]; const people = [ { name: 'steve', teams: [ { name: 'pirates', beers: ['100'] }, { name: 'penguins', beers: ['300'] } ] }, { name: 'jim', teams: [ { name: 'indians', beers: ['200'] }, { name: 'blue jackets', beers: ['100', '400'] } ] } ]; let newPeople = people.map(fan => { let teams = fan.teams.map(team => { let beer = team.beers.map(beer => beers.filter(brand => brand.id === beer)[0]); return { name: team.name, beers: beer } }); return { name: fan.name, teams: teams } }); console.log(newPeople);

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