我正在学习 Javascript,我对通过 ID 加入两个对象数组感到怀疑,我可以加入这两个对象,但结果不是我所期望的。
所以,我有这两个对象数组:
"product": [
{
"id": "1000",
"code": "f230fh0g3",
"name": "Bamboo Watch",
"description": "Product Description",
"image": "bamboo-watch.jpg",
"price": 65,
"category": "Accessories",
"quantity": 24,
}
]
"orders": [
{
"id": "1000",
"productID": "f230fh0g3",
"date": "2020-09-13",
"amount": 65,
"quantity": 1,
},
{
"id": "1000",
"productID": "f230fh0g3",
"date": "2020-09-13",
"amount": 65,
"quantity": 1,
},
]
我想通过键(id)加入两者以获得一个像这样的数组:
"product": [
{
"id": "1000",
"code": "f230fh0g3",
"name": "Bamboo Watch",
"description": "Product Description",
"image": "bamboo-watch.jpg",
"price": 65,
"category": "Accessories",
"quantity": 24,
"orders": [
{
"id": "1000",
"productCode": "f230fh0g3",
"date": "2020-09-13",
"amount": 65,
"quantity": 1,
"customer": "David James",
"status": "PENDING"
},
{
"id": "1001",
"productCode": "f230fh0g3",
"date": "2020-05-14",
"amount": 130,
"quantity": 2,
"customer": "Leon Rodrigues",
"status": "DELIVERED"
},
]
},
{
"id": "1001",
"..."
"orders": [
{
"id": "1001",
"..."
}
]
}]
是否可以以这种方式映射这些数组?提前致谢
对的,这是可能的。可以.map()
和.filter()
一起使用。假设您有变量中的产品和product
变量中的订单order
,您可以像这样计算您的组合列表:
const result = products.map(
product => ({
...product,
orders: orders.filter(
({ productID }) => productID === product.id
)
})
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句