根据元素将数组组合成对象

Combine arrays into objects depending on elements

我有两个数组,数组 1 包含部分,数组 2 包含对象,目标是根据类型(配菜或酱汁)将对象中数组 2 中的对象插入到数组 1 中:数组 2 中包含元素 type:Sauces 的每个对象都应设置在数组 1 的对象内的数组中 type:Sauces,依此类推。我尝试使用 forEach 函数,但由于我对 JavaScript 比较陌生,所以我不知道如何进行

数组 1(部分)

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

数组 2(对象列表)

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",
  },
]

这就是我要实现的目标:

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",       
                 },
               ]
      },
    ]

我将 Array1 命名为类别 我命名 Array2 = elements 您需要在每个地图上进行映射。

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

这应该适合你:

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