如何从JavaScript的boxes与items数组生成指定结构的final数组
问题需求:将两个JavaScript数组转换为指定结构的数组
原始数组
boxes数组
const boxes=[ { "trolleyNo": "345A", "trolleyItems": [ { "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bar Cart - Liquor, Liqueur", "value": "Bar Cart - Liquor, Liqueur", "label": "Bar Cart - Liquor, Liqueur" }, { "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bar Cart - Beer & Wine", "value": "Bar Cart - Beer & Wine", "label": "Bar Cart - Beer & Wine" }, { "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bread Basket & Tongs", "value": "Bread Basket & Tongs", "label": "Bread Basket & Tongs" }, { "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Crew Store - Cookies, juices, etc", "value": "Crew Store - Cookies, juices, etc", "label": "Crew Store - Cookies, juices, etc" } ], "cartType": "fullCart", "index": "FC-093" }, { "trolleyNo": "560S", "trolleyItems": [ { "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bar Cart - Beer & Wine", "value": "Bar Cart - Beer & Wine", "label": "Bar Cart - Beer & Wine" }, { "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bread Basket & Tongs", "value": "Bread Basket & Tongs", "label": "Bread Basket & Tongs" }, { "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Crockery - Full Plates", "value": "Crockery - Full Plates", "label": "Crockery - Full Plates" } ], "cartType": "halfCart", "index": "FC-093" } ]
items数组
const items= [ { "_id": "646d96f669cad73dc5d14a25", "name": "Bar Cart - Beer & Wine", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" }, { "_id": "646d96f669cad73dc5d14a24", "name": "Bar Cart - Liquor, Liqueur", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" }, { "_id": "646d96f669cad73dc5d14a2b", "name": "Bread Basket & Tongs", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" }, { "_id": "646d96f669cad73dc5d14a2d", "name": "Crew Meals", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" }, { "_id": "646d96f669cad73dc5d14a31", "name": "Crew Store - Cookies, juices, etc", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" }, { "_id": "646d96f669cad73dc5d14a32", "name": "Crockery - Full Plates", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" } ]
目标数组结构
const final= [ { "cartId": "full", "itemsCategory": [ { "categoryId": "645bbe9141332374a05919d2" }, { "categoryId": "645bbf960e37e37b5c18e37e" } ] }, { "cartId": "half", "itemsCategory": [ { "categoryId": "645bc57dd374a392f8226708" }, { "categoryId": "645bc588d374a392f8226709" } ] } ]
转换规则
- cartId映射规则:将boxes数组中元素的
cartType字段转换,"fullCart"转为"full","halfCart"转为"half" - itemsCategory生成规则:遍历boxes中每个元素的
trolleyItems数组,将每个元素的name与items数组中对象的name匹配,取匹配对象的_id作为categoryId的值,组成itemsCategory数组
内容的提问来源于stack exchange,提问作者rishzeta
相关产品推荐
相关产品推荐

