You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将对象数组转换为每个对象保留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 }));
});

实现逻辑说明

  1. 使用flatMap/reduce遍历原数组,可直接将每个元素返回的子数组合并为一维数组,无需额外手动扁平化处理
  2. 对每个原对象先拆分出固定保留的公共属性,和需要拆分的剩余属性
  3. 遍历剩余属性,逐个和公共属性组合生成新对象,最后合并为结果数组

内容的提问来源于stack exchange,提问作者zef99_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:15:04