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

JavaScript:将嵌套对象转换为自定义对象数组

嵌套对象转指定结构数组实现方案

输入对象

const test = {
  a: { name: "A", selected: [1, 2, 3], display: [1, 2, 3] },
  b: { name: "B", selected: [4, 5, 6], display: [4, 5, 6] },
  c: { name: "C", selected: [7, 8, 9], display: [7, 8, 9] },
  d: { name: "D", selected: [], display: [] }
};

期望输出

const output = [
  { field: "A", selectedValues: [1, 2, 3] },
  { field: "B", selectedValues: [4, 5, 6] },
  { field: "C", selectedValues: [7, 8, 9] }
];

需求说明

  • 输入对象子项的name属性作为结果对象的field值
  • 输入对象子项的selected数组作为结果对象的selectedValues值
  • 仅保留selected数组非空的项,若所有项selected都为空则返回空数组

你的代码问题

当前实现存在三个核心问题:

  1. field错误使用了输入对象的key(比如a),而非子项的name属性
  2. selectedValues直接赋值了整个子对象,没有提取目标selected数组
  3. 未过滤掉selected为空数组的项

正确实现代码

const result = Object.entries(test)
  // 转换为目标结构的对象
  .map(([_, value]) => ({
    field: value.name,
    selectedValues: value.selected
  }))
  // 过滤掉selectedValues为空的项
  .filter(item => item.selectedValues.length > 0);

console.log(result);

代码说明

  1. Object.entries(test):将输入对象拆解为[key, 子对象]格式的数组
  2. map遍历:把每个子对象转换为需求指定的结构,取name作为field、selected作为selectedValues
  3. filter过滤:只保留selectedValues数组长度大于0的项,自动排除空数组条目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:10:35