如何自动生成带自增itemId的allocatedItem对象数组?
解决方案
可以通过Object.values()结合数组的map()方法实现自动遍历并生成目标数组,无需手动逐个访问g中的每个Galley对象,具体实现如下:
完整代码示例
const g = { "Galley1": { "id": "Box-1", "rollNo": "", "name": "Flasks", "bgColorCode": "#058af7" }, "Galley2": { "id": "Box-2", "rollNo": "", "name": "Perishable and Water Cart", "bgColorCode": "#f5f102" }, "Galley3": { "id": "Box-3", "rollNo": "", "name": "Drystores and Cups", "bgColorCode": "#6e6e67" }, "Galley4": { "id": "Box-5", "rollNo": "", "name": "Vaccum Flasks", "bgColorCode": "#c0c0c0" }, "Galley11": { "id": "Box-2", "rollNo": "", "name": "Perishable and Water Cart", "bgColorCode": "#f5f102" }, "Galley10": { "id": "Box-7", "rollNo": "", "name": "Flexi SMU", "bgColorCode": "#058af7" }, "Galley9": { "id": "Box-6", "rollNo": "", "name": "ROB SMU", "bgColorCode": "#6e6e67" }, "Galley8": { "id": "Box-8", "rollNo": "", "name": "Dessert Cart", "bgColorCode": "#c0c0c0" }, "Galley7": { "id": "Box-9", "rollNo": "", "name": "Liquor", "bgColorCode": "#f5f102" }, "Galley6": { "id": "Box-10", "rollNo": "", "name": "Meals Tray", "bgColorCode": "#009933" }, "Galley5": { "id": "Box-11", "rollNo": "", "name": "Bottles", "bgColorCode": "#058af7" } }; // 生成目标数组 const allocatedItem = Object.values(g).map((galleyItem, index) => ({ cartId: galleyItem.name, itemId: (index + 1).toString() })); console.log(allocatedItem);
实现说明
- 提取所有Galley对象:
Object.values(g)会返回g对象中所有属性值组成的数组,自动包含所有Galley对象,无需手动指定每个GalleyX键名。 - 遍历生成目标元素:使用
map()方法遍历上述数组,map的第二个参数index是当前元素的索引(从0开始),将index + 1转为字符串即可得到自动递增的itemId。 - 结构映射:每个遍历到的Galley对象,直接取其
name作为cartId,结合生成的itemId组成目标对象,最终所有对象会被收集为allocatedItem数组。
这种方式完全满足自动遍历、itemId递增的需求,代码简洁且易于维护。
内容的提问来源于stack exchange,提问作者bugsmasher
相关产品推荐
相关产品推荐

