Search code examples
javascriptarraysjavascript-objects

How to create multiple arrays by looping through an array of multiple objects


usually I refrain from asking questions but I can't really find a question similar to mine out here.

I have 2 vars, one (var subjects) for items, characters and places, the other (var books) for books, let's say Harry Potter.

{ id: 1, name: "Sorcerer's Stone", total: "333", date: "2000", set_no: ["1", "2", "IT1", "IT2", "PL1", "PL2"] },
{ id: 2, name: "Secret Chamber", total: "333", date: "2001", set_no: ["1", "2", "6", "IT1", "IT3", "PL1", "PL4"] },
{ id: 3, name: "Prisoner of Azkaban", total: "333", date: "2002", set_no: ["1", "2", "3",  "IT1", "IT2", "PL1", "PL3", "PL6"] }
]

var subjects = [
{ id: 1, name_id: [1,2,3], name: "Harry", code: "1" },
{ id: 2, name_id: [1,2,3], name: "Hagrid", code: "2" },
{ id: 3, name_id: [3], name: "Sirius", , code: "3" },
...
{ id: 6, name_id: [2], name: "Rat", code: "6" },
...
{ id: 30, name_id: [1,2,3], name: "Golden Snitch", code: "IT1"},
...
]

Of course the list goes on, in reality this is a file where var subjects = 1000 objects and var books = 150 objects.

I've already created the entire database for this, where I made an API call and filled in the "set_no"-array completely for every "book". However, I still have to get all of that data into var subjects, into the name_id array.

How would I do this? Of course in this example I wrote it manually. (but in reality once all data is filled in it'll be close to 15k items, then the real work begins and I refine my API so that it'll be closer to 45k items)

Why do I need this? The code I wrote is for a dropdown list where if I select a book, it'll only reveal the subjects that are relevant to that specific book. Which is what the name_id is for.

Any help would be much appreciated, Thanks in advance! :D


Solution

  • IIUC, you can iterate the subjects array and fill in the name_id value by filtering the books array on whether the set_no includes the code from the subject; then mapping the result of filter to just return the id of the book:

    const books = [
      { id: 1, name: "Sorcerer's Stone", total: "333", date: "2000", set_no: ["1", "2", "IT1", "IT2", "PL1", "PL2"] },
      { id: 2, name: "Secret Chamber", total: "333", date: "2001", set_no: ["1", "2", "6", "IT1", "IT3", "PL1", "PL4"] },
      { id: 3, name: "Prisoner of Azkaban", total: "333", date: "2002", set_no: ["1", "2", "3",  "IT1", "IT2", "PL1", "PL3", "PL6"] }
    ]
    
    const subjects = [
      { id: 1, name_id: [], name: "Harry", code: "1" },
      { id: 2, name_id: [], name: "Hagrid", code: "2" },
      { id: 3, name_id: [], name: "Sirius", code: "3" },
      { id: 6, name_id: [], name: "Rat", code: "6" },
      { id: 30, name_id: [], name: "Golden Snitch", code: "IT1"},
    ]
    
    subjects.forEach(s => s.name_id = books
      .filter(b => b.set_no.includes(s.code))
      .map(({ id }) => id)
    )
    
    console.log(subjects)