Search code examples
lodashreduce

Lodash reduce array of objects from array of objects


I'm trying to get a list of all guideScenes in all sections via

let combinedScenes = _.reduce(sections,
  (prev, section) =>  {return {...prev, ...section.guideScenes}},
  {}
)

It's only returning the first section list, how do I get all of them in there?


Solution

  • const sections = [{guideScenes: ['hello']}, {guideScenes: ['world']}, {guideScenes: ['hi', 'yo']}] 
    
    let combinedScenesObj = _.reduce(sections, (prev, section, index) =>  {
      return {...prev, [index]: [...section.guideScenes]}
    }, {})
    
    console.log('object:', combinedScenesObj)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>

    You were close you needed a key to be added to each array because you were trying to add to an object

    //dummy data
    const sections = [{guideScenes: ['hello']}, {guideScenes: ['world']}, {guideScenes: ['hi', 'yo']}]
    

    if you're wanting to resolve to an object you should give the item a key, for instance, I've used the index in this example

    let combinedScenesObj = _.reduce(sections, (prev, section, index) =>  {
      return {...prev, [index]:[...section.guideScenes]};
    }, {})
    // { 0: ["hello"], 1: ["world"], 2: ["hi", "yo"] }