请求协助将对象数组转换为数组结构,字段值转为数组
把对象字段值转换为数组形式的解决方案
看起来你需要将对象中的单个值(比如字符串类型的title)包装成数组,这里提供两种方案,根据你的具体需求来选:
方案一:仅转换指定字段(比如只处理title)
如果只需要把特定字段改成数组形式,直接遍历原数组,对目标字段进行包装即可:
代码实现
// 你的原始数据 const originalData = [ { "messages": { "m1": { "message": "Relay malfunction found. Cause: moth.", "sender": "ghopper" } }, "title": "Historical Tech Pioneers", "key": "one" } ]; // 仅转换title字段 const convertedData = originalData.map(item => ({ ...item, // 保留其他所有字段 title: [item.title] // 将title包装成数组 })); // 输出结果 console.log(JSON.stringify(convertedData, null, 2));
转换结果
[ { "messages": { "m1": { "message": "Relay malfunction found. Cause: moth.", "sender": "ghopper" } }, "title": [ "Historical Tech Pioneers" ], "key": "one" } ]
方案二:递归转换所有原始类型字段
如果你希望把所有原始类型的字段(比如title、key,还有messages里的message、sender)都转换成数组,可以用递归函数遍历整个对象结构:
代码实现
// 你的原始数据 const originalData = [ { "messages": { "m1": { "message": "Relay malfunction found. Cause: moth.", "sender": "ghopper" } }, "title": "Historical Tech Pioneers", "key": "one" } ]; // 递归转换函数 function wrapPrimitivesInArray(obj) { // 处理数组:遍历每个元素继续转换 if (Array.isArray(obj)) { return obj.map(item => wrapPrimitivesInArray(item)); } // 处理对象:遍历每个属性继续转换 if (typeof obj === 'object' && obj !== null) { const result = {}; for (const key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key]; // 如果是原始类型(非对象/非数组),包装成数组;否则递归处理 if (typeof value !== 'object' || value === null) { result[key] = [value]; } else { result[key] = wrapPrimitivesInArray(value); } } } return result; } // 原始类型直接返回数组包装后的结果 return [obj]; } // 执行转换 const convertedData = wrapPrimitivesInArray(originalData); // 输出结果 console.log(JSON.stringify(convertedData, null, 2));
转换结果
[ { "messages": { "m1": { "message": [ "Relay malfunction found. Cause: moth." ], "sender": [ "ghopper" ] } }, "title": [ "Historical Tech Pioneers" ], "key": [ "one" ] } ]
这样两种方案都覆盖了你的需求,你可以根据实际场景选择合适的方式~
内容的提问来源于stack exchange,提问作者Obi
相关产品推荐
相关产品推荐

