[英]Combine arrays into objects depending on elements
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.我有两个 arrays,Array 1 包含部分,Array 2 包含对象,目标是根据类型(Sides 或 Sauces)将 Array 2 中的对象插入到 Array1 中,例如:每个 object 来自 Array 2 包含元素
type:Sauces
应设置在数组 1 的 object 内的数组中, type:Sauces
等等。 I tried by using the forEach
function but since I'm relatively new to JavaScript I don't know how to proceed我尝试使用
forEach
function 但由于我对 JavaScript 比较陌生,所以我不知道如何继续
Array 1 (Sections)阵列 1(部分)
Array [
Object {
"required": false,
"type": "Sides",
},
Object {
"required": true,
"type": "Sauces",
},
]
Array 2 (List of Objects)数组 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",
},
]
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",
},
]
},
]
I name Array1 = categories I name Array2 = elements You need to map on each.我将 Array1 命名为类别我将其命名为 Array2 = 元素您需要为每个元素添加 map。
const test = categories.map((cat) => {
elements.map((el) => {
if (el.type === cat.type) {
cat.elements.push(el);
}
return el;
});
return cat;
});
console.log(test);
this should work for you:这应该适合你:
arr1.forEach((a,i) => {
a["data"] = arr2.filter(b => b.type == a.type);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.