如何将source_id映射为orderSource对应字符串并生成目标数组
问题描述
现有一个JSON数据集,处理后输出的source_id是数字(1、2),需要替换为对应的字符串(Insta、Retail),最终生成符合要求的数组用于写入Google Sheets。
原始JSON数据
{ "data": [ { "id": 659, "source_id": 1, "created_at": "2023-01-13T06:35:08.000000Z", "products": [ { "name": "532", "properties": [ { "name": "color", "value": "blue" }, { "name": "size", "value": "1" } ] } ] }, { "id": 658, "source_id": 2, "created_at": "2023-01-12T21:36:06.000000Z", "products": [ { "name": "532", "properties": [ { "name": "color", "value": "khaki" }, { "name": "size", "value": "2" } ] } ] } ] }
当前代码
var rows = [], sortOrder = ['fabric', 'color', 'size'], orderSource = [{"Insta" : 1, "Retail" : 2}]; dataSet.forEach((e) => { e.products.forEach((product) => { product.properties = product.properties.sort((a, b) => { return sortOrder.indexOf(a.name) - sortOrder.indexOf(b.name); }); product.properties = sortOrder.map((i => name => product.properties[i].name === name ? product.properties[i++] : {name, value : ''})(0)); rows.push([e.id, e.source_id, new Date(e.created_at).toLocaleDateString('uk-UK'), product.name].concat(product.properties.map(p => p.value)).concat([product.quantity, product.comment])); console.log(rows); }); });
当前输出
[ 659, 1, '13.01.2023', '532', 'blue', '1' ], [ 658, 2, '12.01.2023', '532', 'khaki', '2' ]
期望输出
[ 659, 'Insta', '13.01.2023', '532', 'blue', '1' ], [ 658, 'Retail', '12.01.2023', '532', 'khaki', '2' ]
解决方案
步骤1:重构映射关系
原orderSource的数组包裹对象结构不利于根据数字查找对应字符串,改成键为数字、值为对应名称的对象,实现快速查找:
const sourceMap = { 1: 'Insta', 2: 'Retail' };
步骤2:替换source_id为对应字符串
在构建rows数组时,把e.source_id替换成sourceMap[e.source_id],同时添加默认值处理,避免出现undefined。
修改后的完整代码
var rows = [], sortOrder = ['fabric', 'color', 'size']; // 重构映射关系,数字对应名称 const sourceMap = { 1: 'Insta', 2: 'Retail' }; dataSet.forEach((e) => { e.products.forEach((product) => { product.properties = product.properties.sort((a, b) => { return sortOrder.indexOf(a.name) - sortOrder.indexOf(b.name); }); product.properties = sortOrder.map((i => name => product.properties[i]?.name === name ? product.properties[i++] : {name, value : ''})(0)); // 替换source_id为对应字符串,添加默认值容错 const sourceName = sourceMap[e.source_id] || 'Unknown'; rows.push([ e.id, sourceName, new Date(e.created_at).toLocaleDateString('uk-UK'), product.name ].concat(product.properties.map(p => p.value)).concat([product.quantity, product.comment])); console.log(rows); }); });
说明
- 键值对对象的映射方式比原数组结构查找效率更高,直接通过
sourceMap[数字]就能获取对应名称。 || 'Unknown'是容错处理:如果遇到未定义的source_id,会显示默认值,避免输出异常。- 代码中添加了可选链
product.properties[i]?.name,防止数组越界导致报错。
内容的提问来源于stack exchange,提问作者Олег Дрогуль
相关产品推荐
相关产品推荐

