JavaScript如何基于qty和warehouse属性拆分对象数组元素
JavaScript数组拆分需求实现方案
需求说明
操作给定的对象数组,根据元素的qty和warehouse属性将单个对象拆分为多个对象。
原始数组定义
var response = [ { "name": "test1", "qty": 3, // 按qty拆分为3个对象 "warehouse": { "india": 2, "Usa": 1 } }, { "name": "test2", "qty": 1, "warehouse": { "india": 1 } }, { "name": "test3", "qty": 1, "warehouse": { } } ]
现有代码问题
当前实现存在三个核心问题:
- 使用
map处理会返回嵌套数组,没有做扁平化处理,无法得到一维结果数组 - 生成的拆分对象没有把
qty改为1,也未移除原有的warehouse字段 - 没有处理
warehouse为空的场景,会导致这类条目返回undefined被漏掉
调整后实现代码
const finalResponse = response.flatMap(item => { // 处理仓库为空的场景,直接返回单条调整后的对象 if (Object.keys(item.warehouse).length === 0) { return [{ ...item, qty: 1 }] } const splitItems = [] // 遍历所有仓库按数量生成对应条数的对象 Object.entries(item.warehouse).forEach(([warehouseName, count]) => { for (let i = 0; i < count; i++) { splitItems.push({ name: item.name, qty: 1, [warehouseName]: 1 }) } }) return splitItems })
若运行环境不支持
flatMap,可把flatMap替换为map,最后拼接.flat()方法即可。
最终输出结果
[ { "name": "test1", "qty": 1, "india": 1 }, { "name": "test1", "qty": 1, "india": 1 }, { "name": "test1", "qty": 1, "Usa": 1 }, { "name": "test2", "qty": 1, "india": 1 }, { "name": "test3", "qty": 1, "warehouse": {} } ]
内容的提问来源于stack exchange,提问作者kumar
相关产品推荐
相关产品推荐

