如何将对象数组转换为每个对象保留adId、carBrand加单个其余属性的格式
数组转换实现方案
需求说明
将原对象数组按规则转换:原数组中每个对象拆分为多个新对象,每个新对象固定保留adId、carBrand属性,同时仅携带原对象剩余属性中的单个属性。
实现代码
原生JS实现(无需依赖)
现代环境版本(支持ES2019+)
const originArr = [/* 此处替换为你的原始数组 */]; const convertedArr = originArr.flatMap(item => { // 提取固定保留的公共属性 const { adId, carBrand, ...otherProps } = item; // 遍历剩余属性,每个属性生成一个独立对象 return Object.entries(otherProps).map(([propKey, propValue]) => ({ adId, carBrand, [propKey]: propValue // 如果需要数值转字符串和示例输出一致,替换上一行为:[propKey]: typeof propValue === 'number' ? propValue.toString() : propValue })); });
兼容旧环境版本
如果运行环境不支持flatMap,可使用reduce实现:
const convertedArr = originArr.reduce((total, item) => { const { adId, carBrand, ...otherProps } = item; const itemList = Object.entries(otherProps).map(([propKey, propValue]) => ({ adId, carBrand, [propKey]: propValue })); return total.concat(itemList); }, []);
Lodash实现
const convertedArr = _.flatMap(originArr, item => { // 提取公共属性和剩余属性 const commonProps = _.pick(item, ['adId', 'carBrand']); const restProps = _.omit(item, ['adId', 'carBrand']); // 遍历剩余属性生成新对象 return _.map(restProps, (value, key) => _.assign({}, commonProps, { [key]: value })); });
实现逻辑说明
- 使用
flatMap/reduce遍历原数组,可直接将每个元素返回的子数组合并为一维数组,无需额外手动扁平化处理 - 对每个原对象先拆分出固定保留的公共属性,和需要拆分的剩余属性
- 遍历剩余属性,逐个和公共属性组合生成新对象,最后合并为结果数组
内容的提问来源于stack exchange,提问作者zef99_
相关产品推荐
相关产品推荐

