如何从API嵌套数组中提取指定字段生成目标结构新数组?
解决嵌套数组字段筛选后的显示与结构问题
你的代码逻辑本身是正确的,仅存在两个小问题:
1. 语法错误修正
代码中order[\"lines\"]是不必要的转义写法,直接使用order.lines即可,否则会触发语法报错。
2. 控制台显示问题
你看到的[[Object], [Object]]只是控制台对嵌套对象的默认折叠显示,实际生成的数组结构已经完全符合你的预期。如果想要在控制台看到展开的完整结构,可以用JSON.stringify格式化输出。
修正后的完整代码
const dummyData = [ { orderDate: '20220501', orderNumber: '12345', id: '1', name: 'Customer 1', lines: [ { id: 1, product: 'PRD001', qty: 1}, { id: 2, product: 'PRD002', qty: 3}, ] }, { orderDate: '20220501', orderNumber: '12346', id: '2', name: 'Customer 2', lines: [ { id: 1, product: 'PRD001', qty: 1 }, { id: 2, product: 'PRD002', qty: 2 }, { id: 3, product: 'PRD003', qty: 7 }, { id: 4, product: 'PRD004', qty: 1 }, ] }, { orderDate: '20220502', orderNumber: '12347', id: '3', name: 'Customer 3', lines: [ { id: 1, product: 'PRD001', qty: 1 }, { id: 2, product: 'PRD002', qty: 1 }, { id: 3, product: 'PRD003', qty: 3 }, ] }, ] const currentData = dummyData.map(order => ( { orderDate: order.orderDate, orderNumber: order.orderNumber, lines: order.lines.map(line => ({ product: line.product, qty: line.qty, })) } )) // 格式化输出完整结构 console.log("order", JSON.stringify(currentData, null, 2))
输出结果
运行修正后的代码,你会得到完全符合预期的结构:
[ { "orderDate": "20220501", "orderNumber": "12345", "lines": [ { "product": "PRD001", "qty": 1 }, { "product": "PRD002", "qty": 3 } ] }, { "orderDate": "20220501", "orderNumber": "12346", "lines": [ { "product": "PRD001", "qty": 1 }, { "product": "PRD002", "qty": 2 }, { "product": "PRD003", "qty": 7 }, { "product": "PRD004", "qty": 1 } ] }, { "orderDate": "20220502", "orderNumber": "12347", "lines": [ { "product": "PRD001", "qty": 1 }, { "product": "PRD002", "qty": 1 }, { "product": "PRD003", "qty": 3 } ] } ]
内容的提问来源于stack exchange,提问作者Cem Yeten
相关产品推荐
相关产品推荐

