Search code examples
javascriptarraysdata-structuresmappinglodash

Convert object with single entry to array in Lodash


I'm using lodash to transform a response from a GraphQL. What I've is the following structure:

[[
  { nodes: [ {}, {} ] },
  { nodes: [ {}, {} ] },
  { nodes: [ {}, {}, {} ] },
  { nodes: [ {}, {}, {} ] },
  { nodes: [ {}, {} ] },
  { nodes: [ {}, {}, {} ] },
], [
  { nodes: [ {}, {} ] },
  { nodes: [ {}, {}, {} ] },
  { nodes: [ {}, {}, {} ] },
  { nodes: [ {}, {} ] },
  { nodes: [ {}, {} ] },
  { nodes: [ {}, {}, {} ] },
]]

But what I need is the following structure:

[[
  [ {}, {} ],
  [ {}, {} ],
  [ {}, {}, {} ],
  [ {}, {}, {} ],
  [ {}, {} ],
  [ {}, {}, {} ],
], [
  [ {}, {} ],
  [ {}, {}, {} ],
  [ {}, {}, {} ],
  [ {}, {} ],
  [ {}, {} ],
  [ {}, {}, {} ],
]]

What I've is the following chain:

_.chain(resp.data.data.projects.nodes)
.flatMap('ciVariables')
.value()

Any idea how to get the target structure using the chain in Lodash? I already tried to use flatMap('ciVariables.nodes'), but then all objects are in the top array.


Solution

  • You could use double map.

    First we loop through the outer array, for each array inside we return the value of nodes property.

    const before = [[
      { nodes: [ {}, {} ] },
      { nodes: [ {}, {} ] },
      { nodes: [ {}, {}, {} ] },
      { nodes: [ {}, {}, {} ] },
      { nodes: [ {}, {} ] },
      { nodes: [ {}, {}, {} ] },
    ], [
      { nodes: [ {}, {} ] },
      { nodes: [ {}, {}, {} ] },
      { nodes: [ {}, {}, {} ] },
      { nodes: [ {}, {} ] },
      { nodes: [ {}, {} ] },
      { nodes: [ {}, {}, {} ] },
    ]]
    
    const after = before.map(arr => {
        return arr.map(object => {
        return object.nodes
      })
    })
    
    console.log(after)

    You can also make it into a one-liner

    const after = before.map(arr => arr.map(object => object.nodes))