Home > Mobile >  Combine arrays into objects depending on elements
Combine arrays into objects depending on elements

Time:02-18

I have two arrays, Array 1 containing the sections, and Array 2 containing the objects, the goal is to insert the objects from Array 2 inside the objects into Array1 depending on the type (Sides or Sauces), for example: Each object from Array 2 containing the element type:Sauces should be set in an array inside the object of Array 1 with type:Sauces and so on. I tried by using the forEach function but since I'm relatively new to JavaScript I don't know how to proceed

Array 1 (Sections)

Array [
  Object {
    "required": false,
    "type": "Sides",
  },
  Object {
    "required": true,
    "type": "Sauces",
  },
]

Array 2 (List of Objects)

Array [
  Object {
    "id": 2.01,
    "price": "1",
    "title": "Hot Sauce",   
    "type": "Sauces",       
  },
  Object {
    "id": 2.02,
    "price": 1,
    "title": "Medium Sauce",
    "type": "Sauces",       
  },
  Object {
    "id": 1.01,
    "price": 1,
    "title": "Ranch",
    "type": "Sides",
  },
  Object {
    "id": 1.02,
    "price": 1,
    "title": "Blue Cheese",
    "type": "Sides",
  },
]

this is what I'm trying to achieve:

Array [
      Object {
        "required": false,
        "type": "Sides",
        "data": [
                 Object {
                   "id": 1.01,
                   "price": 1,
                   "title": "Ranch",
                   "type": "Sides",
                 },
                 Object {
                   "id": 1.02,
                   "price": 1,
                   "title": "Blue Cheese",
                   "type": "Sides",
                 },
                ]
      },
      Object {
        "required": true,
        "type": "Sauces",
        "data":[
                 Object {
                  "id": 2.01,
                  "price": "1",
                  "title": "Hot Sauce",   
                  "type": "Sauces",       
                 },
                 Object {
                  "id": 2.02,
                  "price": 1,
                  "title": "Medium Sauce",
                  "type": "Sauces",       
                 },
               ]
      },
    ]

CodePudding user response:

this should work for you:

arr1.forEach((a,i) => {
    a["data"] = arr2.filter(b => b.type == a.type);
})

CodePudding user response:

I name Array1 = categories I name Array2 = elements You need to map on each.

 const test = categories.map((cat) => {
          elements.map((el) => {
            if (el.type === cat.type) {
              cat.elements.push(el);
            }
            return el;
          });
          return cat;
        });
    console.log(test);
  • Related