-1

I have array of array like

{
  "campaigns": [{
      "name": "1st Campaign",
      "books": [{
          "title": "1st book",
          "primary_isbn": "isbn1"
        },
        {
          "title": "2nd book",
          "primary_isbn": "isbn2"
        },
        {
          "title": "3rd book",
          "primary_isbn": "isbn3"
        }
      ]
    },
    {
      "name": "2nd cam",
      "books": [{
          "title": "4th book",
          "primary_isbn": "isbn4"
        },
        {
          "title": "5th book",
          "primary_isbn": "isbn5"
        }
      ]
    }
  ]
}

From above array i need to create new array where each campaign (parent) data converted to number of items per book. So for first item 1st campaign should be converted to 3 items as there are 3 books. so my new array should be

{
  "campaigns": [{
      "name": "1st campaign"
      "title": "1st book",
      "primary_isbn": "isbn1"
    },
    {
      "name": "1st campaign"
      "title": "2nd book",
      "primary_isbn": "isbn2"
    },
    {
      "name": "1st campaign"
      "title": "3rd book",
      "primary_isbn": "isbn3"
    },
    ...
  ]
}

And same structure for 2nd campaign. I am not sure how to approach this problem

I tried this using lodash

_.flattenDeep(data.campaigns.books)
6
  • 3
    Do you have any attempts? Like finding books, campaigns etc. Commented Apr 19, 2019 at 12:35
  • what about map function?? Commented Apr 19, 2019 at 12:36
  • jvm, you need to add in any code you've attempted to your question as minimal reproducible examples. It will likely use a loop of some kind, and access arrays/objects on each iteration to access the information. Commented Apr 19, 2019 at 12:37
  • I did try using lodash using _.flattenDeep(data.campaigns.books but that isn't helping Commented Apr 19, 2019 at 12:39
  • Where does "1st book", "2nd book" in the output come from? Or should that be computed based on the index? Why is primary_isbn different from the input? Commented Apr 19, 2019 at 12:39

1 Answer 1

4

You could use flatMap and map like this:

const input = {campaigns:[{name:"1st Campaign",books:[{title:"1st book",primary_isbn:"isbn1"},{title:"2nd book",primary_isbn:"isbn2"},{title:"3rd book",primary_isbn:"isbn3"}]},{name:"2nd cam",books:[{title:"4th book",primary_isbn:"isbn4"},{title:"5th book",primary_isbn:"isbn5"}]}]};

const campaigns = 
  input.campaigns.flatMap(({ name, books }) => books.map(b => ({ ...b, name })))

console.log({ campaigns })

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.